package cn.pconline.autoclub.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.StatusLine;
import org.apache.http.util.EntityUtils;
import org.gelivable.dao.GeliDao;
import org.gelivable.web.EnvUtils;
import org.gelivable.webmvc.JSONBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.pconline.autoclub.config.SystemConfig;
import cn.pconline.autoclub.entity.Activity;
import cn.pconline.autoclub.entity.Club;
import cn.pconline.autoclub.entity.ClubAddress;
import cn.pconline.autoclub.entity.ClubAwardRecord;
import cn.pconline.autoclub.entity.ClubBrand;
import cn.pconline.autoclub.entity.ClubDispose;
import cn.pconline.autoclub.entity.ClubDraft;
import cn.pconline.autoclub.entity.ClubFocusImg;
import cn.pconline.autoclub.entity.ClubLevel;
import cn.pconline.autoclub.entity.ClubMember;
import cn.pconline.autoclub.entity.ClubNotice;
import cn.pconline.autoclub.entity.ClubStat;
import cn.pconline.autoclub.entity.ClubTotalMember;
import cn.pconline.autoclub.entity.InviteJoin;
import cn.pconline.autoclub.entity.MemberApplication;
import cn.pconline.autoclub.entity.Style;
import cn.pconline.autoclub.entity.Theme;
import cn.pconline.autoclub.entity.UpgradeGift;
import cn.pconline.autoclub.entity.UpgradeGiftReward;
import cn.pconline.autoclub.entity.UpgradeRule;
import cn.pconline.autoclub.entity.User;
import cn.pconline.autoclub.service.ActivityService;
import cn.pconline.autoclub.service.AlbumService;
import cn.pconline.autoclub.service.CensorIntroduceService;
import cn.pconline.autoclub.service.CensorNoticeService;
import cn.pconline.autoclub.service.CheckInService;
import cn.pconline.autoclub.service.ClubAwardRecordService;
import cn.pconline.autoclub.service.ClubBrandService;
import cn.pconline.autoclub.service.ClubDraftService;
import cn.pconline.autoclub.service.ClubLevelService;
import cn.pconline.autoclub.service.ClubModuleService;
import cn.pconline.autoclub.service.ClubService;
import cn.pconline.autoclub.service.ClubStyleService;
import cn.pconline.autoclub.service.ClubUpgradePrizeService;
import cn.pconline.autoclub.service.CommentService;
import cn.pconline.autoclub.service.DynaService;
import cn.pconline.autoclub.service.IntfService;
import cn.pconline.autoclub.service.InviteJoinService;
import cn.pconline.autoclub.service.MemberService;
import cn.pconline.autoclub.service.MessageService;
import cn.pconline.autoclub.service.PetrolService;
import cn.pconline.autoclub.service.StatService;
import cn.pconline.autoclub.service.ThemeService;
import cn.pconline.autoclub.service.TopicService;
import cn.pconline.autoclub.service.UpgradeGiftRewardService;
import cn.pconline.autoclub.service.UpgradeGiftService;
import cn.pconline.autoclub.service.UpgradeRuleService;
import cn.pconline.autoclub.service.UserService;
import cn.pconline.autoclub.util.AppUtils;
import cn.pconline.autoclub.util.DateUtils;
import cn.pconline.autoclub.util.EncodeUtils;
import cn.pconline.autoclub.util.JsonResult;
import cn.pconline.autoclub.util.Pager;
import cn.pconline.autoclub.util.Regex;
import cn.pconline.autoclub.util.RegionUtil;
import cn.pconline.autoclub.util.SearchUrl;
import cn.pconline.autoclub.util.ShortUrlUtil;
import cn.pconline.autoclub.util.StringUtil;
import cn.pconline.autoclub.util.WebUtils;
import cn.pconline.autoclub.util.WhoisUtil;
import cn.pconline.autoclub.util.app.AppControllerStatic;
import cn.pconline.autoclub.util.dyna.AbstractDyna;
import cn.pconline.r.client.EntityBuilder;
import cn.pconline.r.client.ResponseExtractor;
import cn.pconline.r.client.SimpleHttpTemplate;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * 本controller约定：get请求返回页面 post请求返回json
 *
 * @author chensy
 */
@Controller
public class ClubController {

    @Autowired
    private SimpleHttpTemplate simpleHttpTemplate;
    @Autowired
    private ClubService clubService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserAuth userAuth;
    @Autowired
    private MemberService memberService;
    @Autowired
    private AlbumService albumService;
    @Autowired
    private ActivityService activityService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private SystemConfig systemConfig;
    @Autowired
    private TopicService topicService;
    @Autowired
    private ClubAwardRecordService recordService;
    @Autowired
    private ClubUpgradePrizeService prizeService;
    @Autowired
    private CensorNoticeService censorNoticeService;
    @Autowired
    private CensorIntroduceService censorIntroduceService;
    @Autowired
    private ClubLevelService clubLevelService;
    @Autowired
    private StatService statService;
    @Autowired
    private PetrolService petrolService;
    @Autowired
    private IntfService intfService;
    @Autowired
    private ThemeService themeService;
    @Autowired
    private CheckInService checkInService;
    @Autowired
    private DynaService dynaService;
    @Autowired
    private InviteJoinService inviteJoinService;
    @Autowired
    private ClubDraftService clubDraftService;
    @Autowired
    private ClubModuleService clubModuleService;
    @Autowired
    private ClubBrandService clubBrandService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private UpgradeGiftService upgradeGiftService;
    @Autowired
    private UpgradeGiftRewardService upgradeGiftRewardService;
    @Autowired
    private UpgradeRuleService upgradeRuleService;
    @Autowired
    private GeliDao geliDao;
    private static final Logger log = LoggerFactory.getLogger(ClubController.class);
    final static int INPUT_MAX_LENGTH = 30;
    final static int DB_MAX_LENGTH = 255;
    final static int MAX_PAGESIZE = 100;
    final static int MIN_PAGESIZE = 1;
    final static int DEF_SOURCE_AGENT = 2;
    final static String defaultImg = "http://img0.pcauto.com.cn/pcauto/1501/23/5840763_280x140.jpg";
    final static int PAGE_NUM = 1;
    final static int PAGE_SIZE = 20;
    final static int GIFT_PAGE_SIZE = 15;
    /**
     * 显示最新加入的成员数*
     */
    final static int DISPLAY_LASTEST_COUNT = 13;

    /**
     * 需要显示自定义样式效果的页面都需要用到
     *
     * @param req
     * @param clubId
     */
    public static void setClubStyle(HttpServletRequest req, long clubId) {
        ClubStyleService clubStyleService = EnvUtils.getEnv().getBean(ClubStyleService.class);
        Style style = clubStyleService.getStyleByClubId(clubId);
        req.setAttribute("myStyle", style);
    }

    /**
     * ajax操作的错误信息提示
     *
     * @param resp
     * @param msg
     * @param field
     * @
     */
    private void errorMsg(HttpServletResponse resp, String msg, String field) {
        try {
            resp.setCharacterEncoding("UTF-8");
            resp.getWriter().println(
                    new JSONBuilder()
                    .put("statusCode", -1)
                    .put("field", field)
                    .put("message", msg)
                    .toString());
        } catch (IOException ex) {
            log.error("errorMsg response out error");
        }
    }

    /**
     * ajax操作的成功信息提示
     *
     * @param resp
     * @param msg
     * @
     */
    private void successMsg(HttpServletResponse resp, String msg) {
        try {
            resp.setCharacterEncoding("UTF-8");
            resp.getWriter().println(
                    new JSONBuilder()
                    .put("statusCode", 0)
                    .put("message", msg)
                    .toString());
        } catch (IOException ex) {
            log.error("successMsg response out error");
        }
    }

    /**
     * 判断是否登录
     *
     * @param request
     * @param resp
     */
    private User checkAndSetUser(HttpServletRequest request, HttpServletResponse resp) {
        User user = userAuth.getUser(request, resp);
        if (user.getUid() <= 0) {
            if (WebUtils.isGet(request)) {
                try {
                    String url = systemConfig.getUcRoot()
                            + "/login.jsp?return="
                            + request.getRequestURL();
                    if (request.getQueryString() != null) {
                        url += "?" + request.getQueryString();
                    }
                    resp.sendRedirect(url);
                    return null;
                } catch (IOException ex) {
                    log.error("checkAndSetUser error");
                }
            } else {
                errorMsg(resp, "没有登录", "");
                return null;
            }
        }
        request.setAttribute("user", user);
        return user;
    }

    /**
     * 进入申请创建车友会的页面（登录用户即可）
     *
     * @param request
     * @param model
     * @param resp
     * @return
     * @
     */
    @RequestMapping(value = "/club/found.do", method = RequestMethod.GET)
    public String foundPage(HttpServletRequest request, Model model, HttpServletResponse resp) {
        User user = checkAndSetUser(request, resp);
        if (user == null) {
            return null;
        }
        String tip = clubService.checkJoinedClub(user);
        if (StringUtils.isNotEmpty(tip)) {
            request.setAttribute("msg", tip);
            return "/template/club/common/errorPop";
        } else {
            String ip = WhoisUtil.getIp(request);
            JSONObject array = intfService.getPlaceByIp(ip);
            long cityId = 0;
            if (cityId == 0 && array != null) {
                if (cityId == 0 && !array.get("cityCode").toString().equals("null")) {
                    cityId = Integer.parseInt(array.get("cityCode").toString());
                } else if (cityId == 0 && !array.get("areaCode").toString().equals("null")) {
                    cityId = Integer.parseInt(array.get("areaCode").toString());
                }
            }
            ClubDraft clubDraft = clubDraftService.findDraftByUserId(user.getUid());
            List<Theme> themes = themeService.listAllThemes();
            request.setAttribute("clubDraft", clubDraft);
            request.setAttribute("themes", themes);
            request.setAttribute("cityId", cityId == 999999 ? 0 : cityId);
            request.setAttribute("TYPE_AREA", Club.TYPE_AREA);
            request.setAttribute("TYPE_SERIAL", Club.TYPE_SERIAL);
            request.setAttribute("TYPE_THEME", Club.TYPE_THEME);
            return "/template/club/found";
        }
    }

    /**
     * 申请创建车友会的提交成功的反馈页面（登录用户即可）
     *
     * @param request
     * @param model
     * @param resp
     * @return
     * @
     */
    @RequestMapping(value = "/club/foundSuccess.do", method = RequestMethod.GET)
    public String foundSuccessPage(HttpServletRequest request, Model model, HttpServletResponse resp) {
        if (checkAndSetUser(request, resp) == null) {
            return null;
        }
        return "/template/club/foundSuccess";
    }

    /**
     * 申请创建车友会的提交失败的反馈页面（登录用户即可）
     *
     * @param request
     * @param model
     * @param resp
     * @return
     * @
     */
    @RequestMapping(value = "/club/foundFail.do", method = RequestMethod.GET)
    public String foundFailPage(HttpServletRequest request, Model model, HttpServletResponse resp) {
        if (checkAndSetUser(request, resp) == null) {
            return null;
        }
        return "/template/club/foundFail";
    }

    private String checkJoinedClub(User user) {
        int limit = Integer.parseInt(systemConfig.getJoinClubLimit());
        String tip = "";
        int count = userService.updateJoinedClubCount(user);
        if (count >= limit) {
            tip = "您已加入其他车友会，无法创建新的车友会！";
            return tip;
        }
        count += memberService.findMemberApplication(user.getUid(), 0l, true).size();
        if (count >= limit) {
            tip = "您已申请加入其他车友会，正在审核中，无法创建新的车友会！";
            return tip;
        }
        count += clubService.findByFounder(user.getUid(), false).size();
        if (count >= limit) {
            tip = "您申请创建的车友会正在审核中，请耐心等待审核结果！";
            return tip;
        }
        return tip;
    }

    /**
     * 申请创建车友会（登录用户即可）
     *
     * @param request
     * @param model
     * @param resp
     * @
     */
    @RequestMapping(value = "/club/found.do", method = RequestMethod.POST)
    public void found(HttpServletRequest request, Model model, HttpServletResponse resp) {
        //当该方法返回null的时候证明没登录,提示信息已经在checkAndSetUser返回, 只有在POST接口有效
        if (checkAndSetUser(request, resp) == null) {
            return;
        }
        //param
        String name = WebUtils.paramTrim(request, "name", "");
        String retNameMsg = clubService.checkClubName(name);
        if (!"true".equals(retNameMsg)) {
            errorMsg(resp, retNameMsg, "name");
            return;
        }

        String clubUrl = WebUtils.paramTrim(request, "clubUrl", "").replaceAll(" ", "").toLowerCase();
        String retUrlMsg = clubService.checkClubUrl(clubUrl);
        if (!"true".equals(retUrlMsg)) {
            errorMsg(resp, retUrlMsg, "clubUrl");
            return;
        }
        long themeId = WebUtils.paramLong(request, "themeId", 0);
        int clubType = WebUtils.paramInt(request, "clubType", -1);
        long provinceId = WebUtils.paramLong(request, "provinceId", 0);
        String provinceName = WebUtils.paramTrim(request, "provinceName", "");
        if (provinceId != 0 && StringUtils.isBlank(provinceName)) {
            errorMsg(resp, "缺少省份名称", "");
            return;
        } else if (provinceName.length() > INPUT_MAX_LENGTH) {
            errorMsg(resp, "非法省份名称", "");
            return;
        }
        long regionId = RegionUtil.getRegionId(provinceId);
        String regionName = RegionUtil.getRegionName(regionId);
        long cityId = WebUtils.paramLong(request, "cityId", 0);
        String cityName = WebUtils.getAreaPlaceByReq(request, "cityName", "");
        if (cityId != 0 && StringUtils.isBlank(cityName)) {
            errorMsg(resp, "缺少城市名称", "");
            return;
        } else if (cityName.length() > INPUT_MAX_LENGTH) {
            errorMsg(resp, "非法城市名称", "");
            return;
        }
        long brandId = WebUtils.paramLong(request, "brandId", 0);
        String brandName = WebUtils.getAreaPlaceByReq(request, "brandName", "");
        if (StringUtils.isNotBlank(brandName)) {
            brandName = brandName.substring(2, brandName.length());
        }
        if (brandId != 0 && StringUtils.isBlank(brandName)) {
            errorMsg(resp, "缺少品牌名称", "");
            return;
        } else if (brandName.length() > INPUT_MAX_LENGTH) {
            errorMsg(resp, "非法品牌名称", "");
            return;
        }
        long seriesId = WebUtils.paramLong(request, "seriesId", 0);
        String seriesName = WebUtils.paramTrim(request, "seriesName", "");
        if (seriesId != 0 && StringUtils.isBlank(seriesName)) {
            errorMsg(resp, "缺少车系名称", "");
            return;
        } else if (seriesName.length() > INPUT_MAX_LENGTH) {
            errorMsg(resp, "非法车系名称", "");
            return;
        }
        if (provinceId == 0 && cityId != 0) {//非法操作
            errorMsg(resp, "缺少省份", "cityId");
            return;
        }
        if (brandId == 0 && seriesId != 0) {//非法操作
            errorMsg(resp, "缺少品牌", "seriesId");
            return;
        }
        if (clubType == Club.TYPE_AREA) {//
            if (provinceId == 0) {//允许只选省份
                errorMsg(resp, "请选择地区", "cityId");
                return;
            }
            //选了地区，其他不必填
            themeId = 0;
            brandId = 0;
            brandName = "";
            seriesId = 0;
            seriesName = "";
        } else if (clubType == Club.TYPE_SERIAL) {
            if (brandId == 0) {//允许只选品牌
                errorMsg(resp, "请选择品牌/车系", "seriesId");
                return;
            }
            //选了品牌/车系，主题不必填
            themeId = 0;
        } else if (clubType == Club.TYPE_THEME) {
            if (themeId == 0) {
                errorMsg(resp, "请选择主题", "themeId");
                return;
            }
        } else {
            errorMsg(resp, "请选择车友会类型", "clubType");
            return;
        }
        String qqGroup = WebUtils.paramTrim(request, "qqGroup", "");
        String qqGroupMsg = clubService.checkClubQQGroup(qqGroup);
        if (!"true".equals(qqGroupMsg)) {
            errorMsg(resp, qqGroupMsg, "qqGroup");
            return;
        }
        String realName = WebUtils.paramTrim(request, "realName", "");
        if (StringUtils.isBlank(realName)) {
            errorMsg(resp, "请输入姓名", "realName");
            return;
        } else if (realName.length() > INPUT_MAX_LENGTH) {
            errorMsg(resp, "姓名过长", "realName");
            return;
        }
        int gender = WebUtils.paramInt(request, "gender", 0);
        int clubAddressCityId = WebUtils.paramInt(request, "clubAddressCityId", 0);
        int clubAddressProvinceId = WebUtils.paramInt(request, "clubAddressProvinceId", 0);
        String clubAddressProvinceName = WebUtils.paramTrim(request, "clubAddressProvinceName", "");
        String clubAddressCityName = WebUtils.getAreaPlaceByReq(request, "clubAddressCityName", "");
        if (clubAddressProvinceId == 0 && clubAddressCityId != 0) {//非法操作
            errorMsg(resp, "缺少省份", "clubAddressCityId");
            return;
        }
        if (clubAddressProvinceId != 0 && StringUtils.isBlank(clubAddressProvinceName)) {
            errorMsg(resp, "缺少省份名称", "");
            return;
        } else if (clubAddressProvinceName.length() > INPUT_MAX_LENGTH) {
            errorMsg(resp, "非法省份名称", "");
            return;
        }
        if (clubAddressCityId != 0 && StringUtils.isBlank(clubAddressCityName)) {
            errorMsg(resp, "缺少城市名称", "");
            return;
        } else if (clubAddressCityName.length() > INPUT_MAX_LENGTH) {
            errorMsg(resp, "非法城市名称", "");
            return;
        }
        String address = WebUtils.paramTrim(request, "address", "");
        if (address.length() > DB_MAX_LENGTH) {
            errorMsg(resp, "详细地址过长", "address");
            return;
        }
        String postcode = WebUtils.paramTrim(request, "postcode", "");
        if (StringUtils.isNotBlank(postcode) && !postcode.matches(Regex.postcode.value)) {
            errorMsg(resp, "请填写合法的邮编", "postcode");
            return;
        }
        String phone = WebUtils.paramTrim(request, "phone", "");
        if (StringUtils.isBlank(phone)) {
            errorMsg(resp, "请填写手机", "phone");
            return;
        }
        if (!phone.matches(Regex.cellphone.value)
                || phone.matches(Regex.specialPhone.value)) {
            errorMsg(resp, "请填写合法的手机", "phone");
            return;
        }
        String code = WebUtils.paramTrim(request, "code", "");
        if (StringUtils.isBlank(code)) {
            errorMsg(resp, "请输入验证码", "code");
            return;
        }
        if (systemConfig.isNeedCheckCode()) {
            String checkCodeMsg = checkPhoneCode(phone, code);
            if (StringUtils.isNotEmpty(checkCodeMsg)) {
                errorMsg(resp, checkCodeMsg, "code");
                return;
            }
        }

        int agree = WebUtils.paramInt(request, "agree", -1);
        if (agree == -1) {
            errorMsg(resp, "请阅读并同意《中国车友会管理条例》", "agree");
            return;
        }
        User user = userAuth.getUser(request, resp);
        String tip = clubService.checkJoinedClub(user);
        if (StringUtils.isNotEmpty(tip)) {
            errorMsg(resp, tip, "");
            return;
        }
        long userId = user.getUid();
        //创建车友会
        Date currentDate = DateUtils.getNow();
        Club club = new Club();
        club.setType(clubType);
        club.setAdminId(userId);
        club.setAuditAt(null);
        club.setAuditBy(0);
        club.setThemeId(themeId);
        club.setBrandId(brandId);
        club.setBrandName(brandName);
        club.setCityId(cityId);
        club.setCityName(cityName);
        club.setCreateAt(currentDate);
        club.setCreateBy(userId);
        club.setIntroduce("");
        club.setLevelId(0);
        club.setLogo("");
        club.setMemberNum(0);
        club.setName(name);
        club.setProvinceId(provinceId);
        club.setProvinceName(provinceName);
        club.setRegionId(regionId);
        club.setRegionName(regionName);
        club.setReplyNum(0);
        club.setSeriesId(seriesId);
        club.setSeriesName(seriesName);
        club.setStatus(Club.STATUS_UNAUDITED);
        club.setTopicNum(0);
        club.setUpdateAt(currentDate);
        club.setUpdateBy(userId);
        club.setVipNum(0);
        club.setClubUrl(clubUrl);
        club.setQqGroup(qqGroup);
        //车友会联系地址信息
        ClubAddress clubAddress = new ClubAddress();
        clubAddress.setAddress(address);
        clubAddress.setCityId(clubAddressCityId);
        clubAddress.setCityName(clubAddressCityName);
        //clubAddress.setClubId(clubId);
        clubAddress.setName(realName);
        clubAddress.setPhone(phone);
        clubAddress.setPostcode(postcode);
        clubAddress.setProvinceId(clubAddressProvinceId);
        clubAddress.setProvinceName(clubAddressProvinceName);
        clubAddress.setUpdateAt(currentDate);
        clubAddress.setUpdateBy(userId);
        long clubId = clubService.create(club, clubAddress);

        if (clubId > 0) {
            //创建车友会处理情况
            ClubDispose clubDispose = new ClubDispose();
            clubDispose.setClubId(clubId);
            clubService.createClubDispose(clubDispose);
            //验证通过，绑定手机
            intfService.bindPhone(clubAddress.getPhone(), code,
                    WebUtils.cookie(request, systemConfig.getUserSessionName()));
            //同步省市信息到个人中心
            intfService.checkProvinceCity(clubAddressProvinceId,
                    clubAddressCityId,
                    user.getUid(),
                    systemConfig.getUserSessionName(),
                    WebUtils.cookie(request, systemConfig.getUserSessionName()));
            //第一次创建简介，通知审核平台
            censorIntroduceService.notifyCensorSystemCreate(request, club);
            if (user.isComplete() == false) {
                //同步用户信息
                user.setTruename(realName);
                user.setProvinceId(clubAddressProvinceId);
                user.setProvince(provinceName);
                user.setPhone(phone);
                user.setPhoneValidated(1);
                user.setCityId(clubAddressCityId);
                user.setCity(cityName);
            }
            user.setGender(gender);
            userService.updateUser(user);
            successMsg(resp, "提交成功");
        } else {
            errorMsg(resp, "创建失败", "");
        }
    }

    /**
     * 返回验证结果，如果为空串就表示验证通过，否则返回验证信息
     *
     * @param phone
     * @param code
     * @return
     */
    private String checkPhoneCode(String phone, String code) {
        String relUrl = systemConfig.getRoot() + "/ClubController.found.checkPhoneCode";
        String url = systemConfig.getCheckCodeUrl();
        String result = simpleHttpTemplate.post(url, relUrl, null,
                new ResponseExtractor<String>() {
                    @Override
                    public String extractData(HttpResponse response) {
                        StatusLine statusLine = response.getStatusLine();
                        if (statusLine.getStatusCode() == 200) {
                            try {
                                return EntityUtils.toString(response.getEntity());
                            } catch (IOException ex) {
                                log.error("checPhoneCode fail 1!", ex);
                            } catch (ParseException ex) {
                                log.error("checPhoneCode fail 2!", ex);
                            }
                        } else {
                            log.error("checPhoneCode fail statusCode is " + statusLine.getStatusCode());
                            try {
                                log.error(EntityUtils.toString(response.getEntity()));
                            } catch (IOException ex) {
                                log.error("checkAndSetUser error", ex);
                            } catch (ParseException ex) {
                                log.error("checkAndSetUser error", ex);
                            }
                        }
                        return null;
                    }
                },
                EntityBuilder.entity().param("type", "autoClub").param("act", "check").param("mobile", phone).param("verificationCode", code).build(), 3000);
        JSONObject rs = JSONObject.parseObject(result);
        if (rs == null) {
            return "手机验证出错，请稍后重试";
        }
        int c = rs.getIntValue("code");
        if (c == 0) {
            return "";
        }
        return rs.getString("message");
    }

    /**
     * 检查访问参数是否带clubId
     *
     * @param request
     * @return
     */
    private Club checkAndSetClub(HttpServletRequest request) {
        long clubId = WebUtils.paramLong(request, "clubId", 0);
        if (clubId == 0) {
            return null;
        }
        Club club = clubService.getValidClub(clubId);
        if (club == null) {
            return null;
        }
        request.setAttribute("club", club);
        return club;
    }

    /**
     * 检查是否是管理员，并返回实体
     *
     * @param request
     * @param resp
     * @param isOnlyAdmin 是否限制，只能是会长
     */
    private ClubMember checkClubAuth(HttpServletRequest request, HttpServletResponse resp, boolean isOnlyAdmin) {
        User user = userAuth.getUser(request, resp);
        long clubId = WebUtils.paramLong(request, "clubId", 0);
        ClubMember member = memberService.findMember(user.getUid(), clubId);
        if (member == null || (!member.isAdmin() && !member.isViceAdmin())) {
            if (WebUtils.isGet(request)) {
                try {
                    resp.sendError(403);
                    return null;
                } catch (IOException ex) {
                    log.error("error", ex);
                }
            } else {
                errorMsg(resp, "没有权限：非管理员", "");
                return null;
            }
        }
        if (isOnlyAdmin && !member.isAdmin()) {
            if (WebUtils.isGet(request)) {
                try {
                    resp.sendError(403);
                    return null;
                } catch (IOException ex) {
                    log.error("error", ex);
                }
            } else {
                errorMsg(resp, "没有权限：非会长", "");
                return null;
            }
        }
        return member;
    }

    /**
     * 管理车友会信息页（登录管理员才可访问）
     *
     * @param request
     * @param model
     * @param resp
     * @return
     * @
     */
    @RequestMapping(value = "/club/info", method = RequestMethod.GET)
    public String infoPage(HttpServletRequest request, Model model, HttpServletResponse resp) {
        if (checkAndSetUser(request, resp) == null) {
            return null;
        }
        if (checkClubAuth(request, resp, false) == null) {
            return null;
        }
        Club club = checkAndSetClub(request);
        if (club == null) {
            try {
                resp.sendError(404);
                return null;
            } catch (IOException ex) {
                log.error("error", ex);
            }
        }
        ClubController.setClubStyle(request, club.getClubId());
        return "/template/club/info";
    }

    /**
     * 更新车友会基本信息
     *
     * @param request
     * @param model
     * @param resp
     * @
     */
    @RequestMapping(value = "/club/saveInfo", method = RequestMethod.POST)
    public void saveInfo(HttpServletRequest request, Model model, HttpServletResponse resp) {
        //当该方法返回null的时候证明没登录,提示信息已经在checkAndSetUser返回, 只有在POST接口有效
        if (checkAndSetUser(request, resp) == null) {
            return;
        }
        ClubMember member = checkClubAuth(request, resp, false);
        //当member返回null的时候证明权限不足,提示信息已经在checkClubAuth返回,
        if (member == null) {
            return;
        }
        long clubId = WebUtils.paramLong(request, "clubId", 0);
        String introduce = WebUtils.param(request, "introduce", "");
        String qqGroup = WebUtils.paramTrim(request, "qqGroup", "");

        String qqGroupMsg = clubService.checkClubQQGroup(qqGroup, clubId);
        if (!"true".equals(qqGroupMsg)) {
            errorMsg(resp, qqGroupMsg, "qqGroup");
            return;
        }
        if (introduce.length() > 40) {
            errorMsg(resp, "简介最多40个汉字", "introduce");
            return;
        }
        long adminId = member.getUid();
        Club club = clubService.saveInfo(clubId, introduce, qqGroup, adminId);
        //更新完发去审核
        censorIntroduceService.notifyCensorSystemCreate(request, club);
        successMsg(resp, "保存成功");
    }

    /**
     * 修改公告页面（登录管理员才可访问）
     *
     * @param request
     * @param model
     * @param resp
     * @return
     * @
     */
    @RequestMapping(value = "/club/notice", method = RequestMethod.GET)
    public String noticePage(HttpServletRequest request, Model model, HttpServletResponse resp) {
        if (checkAndSetUser(request, resp) == null) {
            return null;
        }
        Club club = checkAndSetClub(request);
        if (club == null) {
            try {
                resp.sendError(404);
                return null;
            } catch (IOException ex) {
                log.error("error", ex);
            }
        }
        if (checkClubAuth(request, resp, false) == null) {
            return null;
        }
        ClubNotice notice = clubService.getNotice(club.getClubId());
        request.setAttribute("notice", notice);
        ClubController.setClubStyle(request, club.getClubId());
        return "/template/club/notice";
    }

    /**
     * 修改公告
     *
     * @param request
     * @param model
     * @param resp
     * @
     */
    @RequestMapping(value = "/club/saveNotice", method = RequestMethod.POST)
    public void saveNotice(HttpServletRequest request, Model model, HttpServletResponse resp) {
        //当该方法返回null的时候证明没登录,提示信息已经在checkAndSetUser返回, 只有在POST接口有效
        if (checkAndSetUser(request, resp) == null) {
            return;
        }
        Club club = checkAndSetClub(request);
        if (club == null) {
            try {
                resp.sendError(404);
                return;
            } catch (IOException ex) {
                log.error("error", ex);
            }
        }
        ClubMember member = checkClubAuth(request, resp, false);
        //当该方法返回null的时候证明权限不足,提示信息已经在checkClubAuth返回,
        if (member == null) {
            return;
        }
        String content = WebUtils.param(request, "content", "");
        if (StringUtil.length(content) > 100) {
            errorMsg(resp, "最多50个汉字或100个字符（字母、数字）", "");
            return;
        }
        ClubNotice notice = clubService.getNotice(club.getClubId());
        if (!notice.getContent().equals(content)) {
            notice = clubService.saveNotice(club.getClubId(), content, member.getUid());
            if (!StringUtils.isBlank(content)) {
                //更新完发动态
                AbstractDyna d = new AbstractDyna();
                d.setClubId(club.getClubId());
                d.setContent(content);
                d.setTargetId(club.getClubId());
                d.setCreateBy(member.getUid());
                d.setCreateName(userService.findUser(member.getUid()).getNickname());
                d.setCreateDate(notice.getUpdateAt());
                long dynaInfoId = dynaService.createNoticeDyna(d, null);
                //发审核
                censorNoticeService.notifyCensorSystemCreate(request, notice, dynaInfoId);

                List<ClubMember> members = memberService.listMemberByClubId(club.getClubId());
                for (ClubMember u : members) {
                    User user = userAuth.getUser(request, resp);
                    if (u.getUid() != user.getUid()) {
                        //会长修改公告，通知用户
                        messageService.send(u.getUser(), MessageService.NEW_NOTICE,
                                messageService.assembleUserUrl(user.getUid(), user.getNickname()), messageService.assembleNoticeUrl(club.getClubUrl(), dynaInfoId, content));
                    }
                }
            }
        }
        successMsg(resp, "保存成功");
    }

    /**
     * 修改车标页面（登录管理员才可访问）
     *
     * @param request
     * @param model
     * @param resp
     * @return
     * @
     */
    @RequestMapping(value = "/club/logo", method = RequestMethod.GET)
    public String logoPage(HttpServletRequest request, Model model, HttpServletResponse resp) {
        if (checkAndSetUser(request, resp) == null) {
            return null;
        }
        Club club = checkAndSetClub(request);
        if (club == null) {
            try {
                resp.sendError(404);
                return null;
            } catch (IOException ex) {
                log.error("error", ex);
            }
        }
        if (checkClubAuth(request, resp, false) == null) {
            return null;
        }
        ClubController.setClubStyle(request, club.getClubId());
        return "/template/club/logo";
    }

    /**
     * 修改车标
     *
     * @param request
     * @param model
     * @param resp
     * @
     */
    @RequestMapping(value = "/club/saveLogo", method = RequestMethod.POST)
    public void saveLogo(HttpServletRequest request, Model model, HttpServletResponse resp) {
        //当该方法返回null的时候证明没登录,提示信息已经在checkAndSetUser返回, 只有在POST接口有效
        if (checkAndSetUser(request, resp) == null) {
            return;
        }
        Club club = checkAndSetClub(request);
        if (club == null) {
            try {
                resp.sendError(404);
                return;
            } catch (IOException ex) {
                log.error("error", ex);
            }
        }
        ClubMember member = checkClubAuth(request, resp, false);
        //当该方法返回null的时候证明权限不足,提示信息已经在checkClubAuth返回,
        if (member == null) {
            return;
        }
        String logo = WebUtils.paramTrim(request, "logo", "");
        if (StringUtils.isBlank(logo)) {
            errorMsg(resp, "请选择图片", "");
            return;
        } else if (logo.length() > DB_MAX_LENGTH) {
            errorMsg(resp, "图片地址过长", "");
            return;
        }
        long adminId = member.getUid();
        clubService.saveLogo(club.getClubId(), logo, adminId);
        successMsg(resp, "保存成功");
    }

    /**
     * 进入焦点图管理页面（登录管理员才可访问）
     *
     * @param request
     * @param model
     * @param resp
     * @return
     * @
     */
    @RequestMapping(value = "/club/focusImg", method = RequestMethod.GET)
    public String focusImgPage(HttpServletRequest request, Model model, HttpServletResponse resp) {
        if (checkAndSetUser(request, resp) == null) {
            return null;
        }
        Club club = checkAndSetClub(request);
        if (club == null) {
            try {
                resp.sendError(404);
                return null;
            } catch (IOException ex) {
                log.error("error", ex);
            }
        }
        if (checkClubAuth(request, resp, false) == null) {
            return null;
        }
        //当该方法返回null的时候证明权限不足,提示信息已经在checkClubAuth返回,
        List<ClubFocusImg> imgList = clubService.getFocusImg(club.getClubId());
        ClubFocusImg focusImg1;
        ClubFocusImg focusImg2;
        ClubFocusImg focusImg3;
        if (imgList != null && !imgList.isEmpty()) {
            focusImg1 = imgList.get(0);
            focusImg2 = imgList.get(1);
            focusImg3 = imgList.get(2);
        } else {
            focusImg1 = new ClubFocusImg();
            focusImg2 = new ClubFocusImg();
            focusImg3 = new ClubFocusImg();
        }
        request.setAttribute("focusImg1", focusImg1);
        request.setAttribute("focusImg2", focusImg2);
        request.setAttribute("focusImg3", focusImg3);
        request.setAttribute("defaultImg", defaultImg);
        ClubController.setClubStyle(request, club.getClubId());
        return "/template/club/focusImg";
    }

    /**
     * 设置默认图片,页面加载时用到
     *
     * @param focusImg
     * @return
     */
    private ClubFocusImg setDefaultImg(ClubFocusImg focusImg) {

        if (StringUtils.isBlank(focusImg.getImgUrl())) {
            focusImg.setImgUrl(defaultImg);
            focusImg.setBlank(false);
        } else {
            focusImg.setBlank(true);
        }
        return focusImg;
    }

    /**
     * 移除默认图片
     *
     * @param imgUrl
     * @return
     */
    private String delDefault(String imgUrl) {
        if (imgUrl.equals(defaultImg)) {
            imgUrl = "";
        }
        return imgUrl;
    }

    /**
     * 删除焦点图
     *
     * @param request
     * @param resp
     */
    @RequestMapping(value = "/club/deleteFocusImg", method = RequestMethod.POST)
    public void deleteFocusImg(HttpServletRequest request, HttpServletResponse resp) {
        //当该方法返回null的时候证明没登录,提示信息已经在checkAndSetUser返回, 只有在POST接口有效
        if (checkAndSetUser(request, resp) == null) {
            return;
        }
        //当该方法返回null的时候证明权限不足,提示信息已经在checkClubAuth返回,
        if (checkClubAuth(request, resp, false) == null) {
            return;
        }
        long focusId = WebUtils.paramLong(request, "imgId", 0);
        if (focusId < 1) {
            errorMsg(resp, "参数错误", "");
        }
        if (clubService.deleteFocusImgById(focusId)) {
            successMsg(resp, "删除焦点图成功");
        } else {
            errorMsg(resp, "删除焦点图失败", "");
        }
    }

    /**
     * 更新车友会焦点图
     *
     * @param request
     * @param model
     * @param resp
     * @
     */
    @RequestMapping(value = "/club/saveFocusImg", method = RequestMethod.POST)
    public void saveFocusImg(HttpServletRequest request, Model model, HttpServletResponse resp) {
        //当该方法返回null的时候证明没登录,提示信息已经在checkAndSetUser返回, 只有在POST接口有效
        if (checkAndSetUser(request, resp) == null) {
            return;
        }
        ClubMember member = checkClubAuth(request, resp, false);
        //当该方法返回null的时候证明权限不足,提示信息已经在checkClubAuth返回,
        if (member == null) {
            return;
        }
        Club club = checkAndSetClub(request);
        if (club == null) {
            try {
                resp.sendError(404);
                return;
            } catch (IOException ex) {
                log.error("error", ex);
            }
        }
        String title1 = WebUtils.param(request, "title1", "");
        String imgUrl1 = delDefault(WebUtils.param(request, "imgUrl1", ""));
        String url1 = WebUtils.param(request, "url1", "");
        String title2 = WebUtils.param(request, "title2", "");
        String imgUrl2 = delDefault(WebUtils.param(request, "imgUrl2", ""));
        String url2 = WebUtils.param(request, "url2", "");
        String title3 = WebUtils.param(request, "title3", "");
        String imgUrl3 = delDefault(WebUtils.param(request, "imgUrl3", ""));
        String url3 = WebUtils.param(request, "url3", "");
        int img1Seq = WebUtils.paramInt(request, "focusImg1Seq", 1);
        int img2Seq = WebUtils.paramInt(request, "focusImg2Seq", 2);
        int img3Seq = WebUtils.paramInt(request, "focusImg3Seq", 3);
        int TITLE_MAX_LENTH = 20;
        String TITLE_MAX_LENTH_TIP = "(20个文字以内)";

        if (StringUtils.isNotBlank(imgUrl1) && (!imgUrl1.equals(defaultImg))) {
            if (imgUrl1.length() > DB_MAX_LENGTH) {
                errorMsg(resp, "第一张焦点图的图片地址过长", "");
                return;
            } else if (StringUtils.isBlank(title1)) {
                errorMsg(resp, "请输入第一张焦点图的标题", "");
                return;
            } else if (title1.length() > TITLE_MAX_LENTH) {
                errorMsg(resp, "第一张焦点图的标题过长" + TITLE_MAX_LENTH_TIP, "");
                return;
            }
            if (StringUtils.isBlank(url1)) {
                errorMsg(resp, "请输入第一张焦点图的链接", "");
                return;
            } else if (url1.matches(Regex.pcautoLink.value) == false) {
                errorMsg(resp, "第一张焦点图的链接只能是太平洋汽车网的链接", "");
                return;
            } else if (url1.length() > DB_MAX_LENGTH) {
                errorMsg(resp, "第一张焦点图的链接过长", "");
                return;
            }
        } else {
            img1Seq = ClubFocusImg.EMPTY_SEQ;
            if (StringUtils.isNotBlank(title1) || StringUtils.isNotBlank(url1)) {
                errorMsg(resp, "第一张焦点图您还没有上传", "");
                return;
            }
        }

        if (StringUtils.isNotBlank(imgUrl2) && (!imgUrl2.equals(defaultImg))) {
            if (imgUrl2.length() > DB_MAX_LENGTH) {
                errorMsg(resp, "第二张焦点图的图片地址过长", "");
                return;
            } else if (StringUtils.isBlank(title2)) {
                errorMsg(resp, "请输入第二张焦点图的标题", "");
                return;
            } else if (title2.length() > TITLE_MAX_LENTH) {
                errorMsg(resp, "第二张焦点图的标题过长" + TITLE_MAX_LENTH_TIP, "");
                return;
            }
            if (StringUtils.isBlank(url2)) {
                errorMsg(resp, "请输入第二张焦点图的链接", "");
                return;
            } else if (url2.matches(Regex.pcautoLink.value) == false) {
                errorMsg(resp, "第二张焦点图的链接只能是太平洋汽车网的链接", "");
                return;
            } else if (url2.length() > DB_MAX_LENGTH) {
                errorMsg(resp, "第二张焦点图的链接过长", "");
                return;
            }
        } else {
            img2Seq = ClubFocusImg.EMPTY_SEQ;
            if (StringUtils.isNotBlank(title2) || StringUtils.isNotBlank(url2)) {
                errorMsg(resp, "第二张焦点图您还没有上传", "");
                return;
            }
        }

        if (StringUtils.isNotBlank(imgUrl3) && (!imgUrl3.equals(defaultImg))) {
            if (imgUrl3.length() > DB_MAX_LENGTH) {
                errorMsg(resp, "第三张焦点图的图片地址过长", "");
                return;
            } else if (StringUtils.isBlank(title3)) {
                errorMsg(resp, "请输入第三张焦点图的标题", "");
                return;
            } else if (title3.length() > TITLE_MAX_LENTH) {
                errorMsg(resp, "第三张焦点图的标题过长" + TITLE_MAX_LENTH_TIP, "");
                return;
            }
            if (StringUtils.isBlank(url3)) {
                errorMsg(resp, "请输入第三张焦点图的链接", "");
                return;
            } else if (url3.matches(Regex.pcautoLink.value) == false) {
                errorMsg(resp, "第三张焦点图的链接只能是太平洋汽车网的链接", "");
                return;
            } else if (url3.length() > DB_MAX_LENGTH) {
                errorMsg(resp, "第三张焦点图的链接过长", "");
                return;
            }
        } else {
            img3Seq = ClubFocusImg.EMPTY_SEQ;
            if (StringUtils.isNotBlank(title3) || StringUtils.isNotBlank(url3)) {
                errorMsg(resp, "第三张焦点图您还没有上传", "");
                return;
            }
        }
        if (StringUtils.isBlank(imgUrl1) && StringUtils.isBlank(imgUrl2) && StringUtils.isBlank(imgUrl3)) {
            errorMsg(resp, "请至少上传一张焦点图", "");
            return;
        }
        long adminId = member.getUid();
        clubService.saveFocusImg(club.getClubId(), adminId,
                title1, url1, imgUrl1, img1Seq,
                title2, url2, imgUrl2, img2Seq,
                title3, url3, imgUrl3, img3Seq);
        successMsg(resp, "保存成功");
    }

    /**
     * 修改收货地址页面（登录的会长才可访问）
     *
     * @param request
     * @param model
     * @param resp
     * @return
     * @
     */
    @RequestMapping(value = "/club/address", method = RequestMethod.GET)
    public String addressPage(HttpServletRequest request, Model model, HttpServletResponse resp) {
        if (checkAndSetUser(request, resp) == null) {
            return null;
        }
        Club club = checkAndSetClub(request);
        if (club == null) {
            try {
                resp.sendError(404);
                return null;
            } catch (IOException ex) {
                log.error("error", ex);
            }
        }
        if (checkClubAuth(request, resp, true) == null) {
            return null;
        }
        ClubAddress address = clubService.getAddress(club.getClubId());
        request.setAttribute("address", address);
        ClubController.setClubStyle(request, club.getClubId());
        return "/template/club/address";
    }

    /**
     * 更新收货地址（登录的会长才可以修改）
     *
     * @param request
     * @param model
     * @param resp
     * @
     */
    @RequestMapping(value = "/club/saveAddress", method = RequestMethod.POST)
    public void saveAddress(HttpServletRequest request, Model model, HttpServletResponse resp) {
        //当该方法返回null的时候证明没登录,提示信息已经在checkAndSetUser返回, 只有在POST接口有效
        if (checkAndSetUser(request, resp) == null) {
            return;
        }
        Club club = checkAndSetClub(request);
        if (club == null) {
            try {
                resp.sendError(404);
                return;
            } catch (IOException ex) {
                log.error("error", ex);
            }
        }

        ClubMember member = checkClubAuth(request, resp, true);
        //当该方法返回null的时候证明权限不足,提示信息已经在checkClubAuth返回,
        if (member == null) {
            return;
        }
        String name = WebUtils.paramTrim(request, "name", "");
        if (StringUtils.isBlank(name)) {
            errorMsg(resp, "请填写收件人", "");
            return;
        } else if (name.length() > INPUT_MAX_LENGTH) {
            errorMsg(resp, "收件人过长", "");
            return;
        }
        long cityId = WebUtils.paramInt(request, "cityId", 0);
        String cityName = WebUtils.getAreaPlaceByReq(request, "cityName", "");
        long provinceId = WebUtils.paramInt(request, "provinceId", 0);
        String provinceName = WebUtils.paramTrim(request, "provinceName", "");
        if (cityId == 0 || provinceId == 0
                || StringUtils.isBlank(provinceName) || StringUtils.isBlank(cityName)) {
            errorMsg(resp, "请选择省份城市", "");
            return;
        }
        String address = WebUtils.paramTrim(request, "address", "");
        if (StringUtils.isBlank(address)) {
            errorMsg(resp, "请填写邮寄地址", "");
            return;
        } else if (address.length() > INPUT_MAX_LENGTH) {
            errorMsg(resp, "邮寄地址过长", "");
            return;
        }
        String postcode = WebUtils.paramTrim(request, "postcode", "");
        if (StringUtils.isBlank(postcode)) {
            errorMsg(resp, "请填写邮编", "");
            return;
        } else if (!postcode.matches(Regex.postcode.value)) {
            errorMsg(resp, "请填写合法的邮编", "");
            return;
        }
        String phone = WebUtils.paramTrim(request, "phone", "");
        if (StringUtils.isBlank(phone)) {
            errorMsg(resp, "请填写手机", "");
            return;
        } else if (!phone.matches(Regex.cellphone.value)
                || phone.matches(Regex.specialPhone.value)) {
            errorMsg(resp, "请填写合法的手机", "");
            return;
        }
        ClubAddress clubAddress = new ClubAddress();
        clubAddress.setAddress(address);
        clubAddress.setCityId(cityId);
        clubAddress.setCityName(cityName);
        clubAddress.setName(name);
        clubAddress.setPhone(phone);
        clubAddress.setPostcode(postcode);
        clubAddress.setProvinceId(provinceId);
        clubAddress.setProvinceName(provinceName);
        long adminId = member.getUid();
        clubService.saveAddress(club.getClubId(), clubAddress, adminId);
        successMsg(resp, "保存成功");

    }

    /**
     * 车友会首页（不需要登录）
     *
     * @param request
     * @param model
     * @param resp
     * @return
     * @
     */
    @RequestMapping(value = "/club/index", method = RequestMethod.GET)
    public String indexPage(HttpServletRequest request, HttpServletResponse resp) {
        long clubId = WebUtils.paramLong(request, "clubId", 0);
        Club club = clubService.getValidClub(clubId);
        if (club == null) {
            try {
                resp.sendError(404);
                return null;
            } catch (IOException ex) {
                log.error("error", ex);
            }
        }
        User user = userAuth.getUser(request, resp);
        request.setAttribute("user", user);
        ClubMember member = memberService.findMember(user.getUid(), clubId);
        boolean isClubAdmin = false;
        boolean isPresident = false;
        if (member != null) {
            isClubAdmin = member.isAdministrator();
            isPresident = member.isAdmin();
        }
        
        String introduce = "";
        if (club.getIntroduce()!=null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(club.getIntroduce());
            introduce = m.replaceAll("");
        }
        
        request.setAttribute("introduce", introduce);
        request.setAttribute("club", club);
        request.setAttribute("pageNo", 1);
        request.setAttribute("isIndex", true);
        request.setAttribute("isMember", member != null);
        request.setAttribute("isLogin", user.getUid() > 0);
        request.setAttribute("isPresident", isPresident);
        request.setAttribute("isClubAdmin", isClubAdmin);
        ClubController.setClubStyle(request, clubId);
        List<Long> modules = clubModuleService.getNormalModuleIdsByClub(clubId);
        request.setAttribute("ACTIVITY", ClubModuleService.MODULE_ID_ACTIVITY);
        request.setAttribute("DIARY", ClubModuleService.MODULE_ID_DIARY);
        request.setAttribute("DYNA", ClubModuleService.MODULE_ID_DYNA);
        request.setAttribute("FOCUSIMG", ClubModuleService.MODULE_ID_FOCUS_IMG);
        request.setAttribute("PHOTO", ClubModuleService.MODULE_ID_PHOTO);
        request.setAttribute("modules", modules);
        return "/template/club/index";
    }

    /**
     * ********* 提供给个人中心的接口 ****************
     */
    /**
     * 升级车友会
     *
     * @author fxr
     * @param request
     * @param response
     * @return
     * @
     */
    @ResponseBody
    @RequestMapping(value = "/club/upgradeClubLevel.do", method = RequestMethod.POST)
    public void upgradeClubLevel(HttpServletRequest request, HttpServletResponse response) {
        long clubId = WebUtils.paramLong(request, "clubId", 0);
        long levelId = WebUtils.paramLong(request, "levelId", 0);
        String giftStr = WebUtils.param(request, "giftStr", "");
        
        if (levelId < 1) {
            this.errorMsg(response, "参数非法!", null);
            return;
        }
        if (giftStr.equals("")) {
            this.errorMsg(response, "参数非法!", null);
            return;
        }
        Club oldclub = clubService.getValidClub(clubId);
        if (oldclub == null) {
            this.errorMsg(response, "车友会不存在!", null);
            return;
        }
        // 是否登录
        User user = userAuth.getUser(request, response);
        if (user == null || user.getUid() == 0) {
            this.errorMsg(response, "您是游客，请登录后再操作", null);
            return;
        }
        // 是否会长
        ClubMember clubMember = memberService.findMember(user.getUid(), clubId);
        if (clubMember == null || !clubMember.isAdmin()) {
            this.errorMsg(response, "您不是会长，无法操作!", null);
            return;
        }

        if (oldclub.getStatus() == Club.STATUS_LOCK) {
            this.errorMsg(response, "车友会已经被锁定，无法操作!", null);
            return;
        }

        if (oldclub.getStatus() == Club.STATUS_REJECTED) {
            this.errorMsg(response, "车友会已经被封，无法操作!", null);
            return;
        }
        int result = clubLevelService.isUpLevel(oldclub);
        if (result != 5) {
            this.errorMsg(response, "该车友会未满足升级条件!", null);
            return ;
        }
        //升级操作
        Map<Boolean, String> info = clubService.updateClubLevel(clubId, levelId);
        if (info.containsKey(true)) {
            ClubAwardRecord c = recordService.findByClubId(clubId, levelId);
            Club club = clubService.getValidClub(clubId);
            if (club == null) {
                this.errorMsg(response, "车友会已经被锁定，无法操作!", null);
                return;
            }
            if (c == null) {
            	this.errorMsg(response, "请先填写收货信息!", null);
                return;
            }
            if (c.getReceived() == ClubAwardRecord.RECEIVED_NO) {
                c.setReceived(ClubAwardRecord.RECEIVED_YES);
                c.setAcceptDate(DateUtils.getNow());//更新领奖时间
                recordService.update(c);
                JSONArray jsonArray = JSONArray.parseArray(giftStr);
                StringBuilder giftInfo = new StringBuilder();
                if (jsonArray != null && !jsonArray.isEmpty()) {
                	ClubAwardRecord awardRecord = recordService.findByClubId(clubId, levelId);
                	for(int i=0; i<jsonArray.size(); i++){
                		JSONObject jsonObject = jsonArray.getJSONObject(i);
                		UpgradeGiftReward giftReward = new UpgradeGiftReward();
                		long giftId = jsonObject.getLongValue("giftId");
                		int num = jsonObject.getIntValue("num");
                		long totalValuePoint = jsonObject.getLongValue("valuePoint");
                		UpgradeGift gift = upgradeGiftService.findUpgradeGift(giftId);
                		if(awardRecord != null){
                			giftReward.setAddress(awardRecord.getAddress());
                			giftReward.setClubId(clubId);
                			giftReward.setCreateAt(new Date());
                			giftReward.setGiftId(giftId);
                			giftReward.setNum(num);
                			giftReward.setPhone(awardRecord.getPhone());
                			giftReward.setValuePoint(totalValuePoint);
                			giftReward.setTrueName(awardRecord.getName());
                			giftReward.setUserId(user.getUid());
                			giftReward.setUpdateAt(new Date());
                			giftReward.setPostcode(awardRecord.getPostalCode());
                			giftReward.setStatus(UpgradeGiftReward.STATUS_NOSEND);
                			long id = geliDao.create(giftReward);
	            			if (id > 0) {
	            				if(gift !=null){
	            					if (gift.getCurNum() > 0) {
	            		                 gift.setCurNum(gift.getCurNum() - num);
	            		                 //会长礼品信息
	            		                 giftInfo.append(gift.getName()).append("x").append(num).append(",");
	            		            }
	            		        	upgradeGiftService.updateUpgradeGift(gift);
	            				}
	            		    }
                		}
                		
                		
                	}
                }
                this.successMsg(response, "领取成功，太平洋汽车网会尽快将福利快递给您，请您注意查收！");
                //给所有车友会成功发送升级信息,只有在第一次升级的时候才会发信息
                clubLevelService.setMsgToMember(clubId, giftInfo.toString());
                //升级成功发MQ到论坛同步任务状态
                clubLevelService.sendUpgrade(club); 
            } else if (c.getReceived() == ClubAwardRecord.RECEIVED_YES) {
                this.errorMsg(response, "该级别福利已领取", null);
            } else {
                this.errorMsg(response, "车友会升级失败", null);
            }
        } else {
            this.errorMsg(response, info.get(false), null);
        }

    }

    /**
     * 等级福利列表
     *
     * @param request
     * @param resp
     * @return
     * @
     */
    @RequestMapping(value = "/club/levelPrizes", method = RequestMethod.GET)
    public String levelPrizes(HttpServletRequest request, HttpServletResponse resp) {
        long clubId = WebUtils.paramLong(request, "clubId", 0);
        Club club = clubService.getValidClub(clubId);
        if (club == null) {
            try {
                resp.sendError(404);
                return null;
            } catch (IOException ex) {
                log.error("error", ex);
            }
        }
        User user = userAuth.getUser(request, resp);
        if (!memberService.isClubOwner(user.getUid(), clubId)) {
            try {
                resp.sendError(403);
                return null;
            } catch (IOException ex) {
                log.error("error", ex);
            }
        }
        int isValid = clubLevelService.isUpLevel(club);
        ClubLevel nextLevel = clubLevelService.getNextLevel(club.getLevelId());
        if (isValid == 5 &&  nextLevel != null) {
              Pager<UpgradeGift> pager = upgradeGiftService.pageUpgradeGift(1, GIFT_PAGE_SIZE, nextLevel.getLevelId());
              ClubAwardRecord awardRecord = recordService.findByClubId(clubId, nextLevel.getLevelId());
              UpgradeRule rule = upgradeRuleService.findUpgradeRuleByLevelId(nextLevel.getLevelId());
              int descNum = 1;
              if(rule != null){
	              	String[] ruleDescArra = rule.getRuleDesc().split("\r\n");
	              	String ruleDesc = "";
	              	for(String str : ruleDescArra){
	              		ruleDesc += "<p class='sum'>"+descNum+"、"+str+"</p>";
	              		descNum++;
	              	}
	              	rule.setRuleDesc(ruleDesc);
              }
              
              long requireValuePoint = 0;
              if (nextLevel.getLevelId() == ClubLevel.LEVEL_ONE && pager.getResultList() != null && !pager.getResultList().isEmpty()) {
                  for(UpgradeGift upgradeGift : pager.getResultList()){
                  	if(upgradeGift.getIsRequired() == UpgradeGift.REQUIRED_YES){
                  		requireValuePoint += upgradeGift.getValuePoint();
                  	}
                  }
              }

              request.setAttribute("isValid", isValid);
              request.setAttribute("clubLevel", nextLevel);
              request.setAttribute("pager", pager);
              request.setAttribute("address", awardRecord);
              request.setAttribute("rule", rule);
              request.setAttribute("requireValuePoint", requireValuePoint);
              request.setAttribute("descNum", descNum);
              request.setAttribute("levelId", nextLevel.getLevelId());
              request.setAttribute("isValid", isValid);
              request.setAttribute("clubId", clubId);
                      request.setAttribute("myClubUrl", club.getClubUrl());
        } else {
            try {
                resp.sendError(404);
                return null;
            } catch (IOException ex) {
                log.error("error", ex);
            }
        }
        
        return "template/club/common/upgradeLevel";
    }

    /**
     * 升级车友会时修改页面跳转
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/club/toEditAddress", method = RequestMethod.GET)
    public String toEditAddress(HttpServletRequest req, HttpServletResponse resp) {
        long clubId = WebUtils.paramLong(req, "clubId", 0);
        long levelId = WebUtils.paramLong(req, "levelId", 0);
        if (clubService.getValidClub(clubId) == null || levelId < 1) {
            try {
                resp.sendError(404);
                return null;
            } catch (IOException ex) {
                log.error("error", ex);
            }
        }
        Club club = checkAndSetClub(req);
        User user = userAuth.getUser(req, resp);
        if (!memberService.isClubOwner(user.getUid(), clubId)) {
            try {
                resp.sendError(403);
                return null;
            } catch (IOException ex) {
                log.error("error", ex);
            }
        }
        ClubLevel nextLevel = clubLevelService.getNextLevel(club.getLevelId());
        ClubAwardRecord awardRecord = recordService.findByClubId(clubId, nextLevel.getLevelId());

        req.setAttribute("clubId", clubId);
        req.setAttribute("clubAddress", awardRecord);
        req.setAttribute("levelId", levelId);
        return "template/club/common/tipsForm";
    }

    /**
     * 修改收货地址
     *
     *
     * @param request
     * @param resp
     * @return
     * @
     */
    @RequestMapping(value = "/club/updateAddress", method = RequestMethod.POST)
    public String updateAddress(HttpServletRequest request, HttpServletResponse resp) {
        try {
            long clubId = WebUtils.paramLong(request, "clubId", 0);
            long levelId = WebUtils.paramLong(request, "levelId", 0);
            Club club = clubService.getValidClub(clubId);
            if (club == null) {
                this.errorMsg(resp, "找不到该车友会", null);
                return null;
            }
            // 是否登录
            User user = userAuth.getUser(request, resp);
            if (user == null || user.getUid() == 0) {
                this.errorMsg(resp, "您是游客，请登录后再操作", null);
                return "redirect:" + systemConfig.getUcRoot() + "/login.jsp?return="
                        + request.getRequestURL()
                        + "?clubId=" + clubId;
            }
            // 是否会长
            ClubMember clubMember = memberService.findMember(user.getUid(), clubId);
            if (clubMember == null) {
                this.errorMsg(resp, "您不是该车友会成员，无法操作!", null);
                return null;
            }
            if (!clubMember.isAdmin()) {
                this.errorMsg(resp, "您不是会长，无法操作!", null);
                return null;
            }
            String name = WebUtils.paramTrim(request, "name", "");
            String phone = WebUtils.paramTrim(request, "phone", "");
            String address = WebUtils.paramTrim(request, "address", "");
            String postalCode = WebUtils.paramTrim(request, "postalCode", "");
            if (StringUtils.isEmpty(name) || name.length() > 20) {
                this.errorMsg(resp, "名字不能为空或名字过长", null);
                return null;
            }
            if (StringUtils.isEmpty(phone) || phone.length() > 20) {
                this.errorMsg(resp, "联系方式不能为空或过长", null);
                return null;
            }
            if (StringUtils.isEmpty(address) || address.length() > 100) {
                this.errorMsg(resp, "地址不能为空或地址过长", null);
                return null;
            }
            if (StringUtils.isEmpty(postalCode) || postalCode.length() > 6) {
                this.errorMsg(resp, "邮编不能为空或邮编过长", null);
                return null;
            }
            ClubAwardRecord awardRecord = recordService.findByClubId(clubId, levelId);

            if (awardRecord == null) {
                int isUp = clubLevelService.isUpLevel(club);
                if (isUp < 4 && isUp > 0) {
                    this.errorMsg(resp, "未达到领取福利标准，无法修改收货人信息", null);
                    return null;
                } else if (isUp == 5) {
                    ClubAwardRecord awRecord = new ClubAwardRecord();
                    awRecord.setClubId(clubId);
                    awRecord.setLevelId(levelId);
                    awRecord.setUpdateTime(DateUtils.getNow());
                    awRecord.setName(name);
                    awRecord.setPhone(phone);
                    awRecord.setAddress(address);
                    awRecord.setPostalCode(postalCode);
                    recordService.create(awRecord);
                    this.successMsg(resp, "修改成功");
                }
            } else if (awardRecord.getReceived() == ClubAwardRecord.RECEIVED_YES) {
                this.errorMsg(resp, "该级别福利已经领取，无法修改收货人信息！", null);
                return null;
            } else if (awardRecord.getReceived() == ClubAwardRecord.RECEIVED_NO) {
                awardRecord.setName(name);
                awardRecord.setPhone(phone);
                awardRecord.setAddress(address);
                awardRecord.setPostalCode(postalCode);
                recordService.update(awardRecord);
                this.successMsg(resp, "修改成功");
            }
        } catch (Exception ex) {
            this.errorMsg(resp, "修改出错了", null);
        }
        return null;
    }

//    private boolean validClubAwardRecord(ClubAwardRecord c) {
//        String name = c.getName();
//        String phone = c.getPhone();
//        String address = c.getAddress();
//        String postalCode = c.getPostalCode();
//        if (StringUtils.isEmpty(name) || name.length() > 20) {
//            return false;
//        }
//        if (phone == null || "".equals(phone) || phone.length() > 20) {
//            return false;
//        }
//        if (address == null || "".equals(address) || address.length() > 100) {
//            return false;
//        }
//        if (postalCode == null || "".equals(postalCode) || postalCode.length() > 6) {
//            return false;
//        }
//        return true;
//    }
    /**
     * 根据用户ID或者地区ID获取车友会列表，3.0 app首页专用暂时性优化，下一版本 全部的接口要重新审视和设计
     *
     * 逻辑： 未登录用户：返回地区推荐列表 已登录未申请也未加入的用户：返回地区推荐列表 已登录已加入用户：返回已加入的车友会会信息，不需要推荐列表了
     * 已登录已申请用户：返回申请的车友会会信息，加上地区推荐列表
     *
     * @throws IOException
     *
     */
    @ResponseBody
    @RequestMapping(value = "/club/getClubByUIdOrRegionId.do", method = RequestMethod.GET)
    public void getClubByUIdOrRegionIdNew(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        WebUtils.setEncoding(req, resp);
        String callback = WebUtils.param(req, "callback", "");
        int isMySelf = WebUtils.paramInt(req, "isMine", 0);
        long provinceId = WebUtils.paramInt(req, "provinceId", 0);
        long cityId = WebUtils.paramInt(req, "cityId", 0);
        long userId = WebUtils.paramLong(req, "userId", 0);
        String ip = WhoisUtil.getIp(req);
        String ips = WebUtils.paramTrim(req, "ip", "");
        int sourceAgent = WebUtils.paramInt(req, "source_agent", 2);
        if (StringUtils.isNotBlank(ips)) {
            ip = ips;
        }
        int recommandListNum = 15;

        List<Club> recommendClubs = null;//最终推荐列表        
        //int isJoin = 0;//数据类型 0 已经加入车友会，1 审核中车友会，2地区推荐车友会 
        JSONObject json = new JSONObject();
        User user = null;
        if (userId > 0) {
            user = userService.findUser(userId);
        }

        List<MemberApplication> memberApplications = null;
        Club clubJoined = null;
        Club clubApplied = null;

        //生成用户相关的club信息
        if (user != null && user.getUid() > 0) {
            json.put("userId", user.getUid());
            //先检查是否已加入，访问频率：未登录 > 未申请/未加入 > 已加入 > 未加入已申请
            ClubMember clubMember = memberService.findClubMemberByUserId(user.getUid());
            if (clubMember != null) {
                clubJoined = clubService.getClub(clubMember.getClubId());
                JSONObject clubJoinedObject = parseClubJSON(clubJoined, user, sourceAgent);
                Map<String, Object> map = clubService.getAdminTypeAndIdByMember(clubMember, memberApplications, clubJoined);
                int type = (Integer) map.get("adminType");
                clubJoinedObject.put("adminType", type);
                clubJoinedObject.put("memberId", map.get("memberId"));
                if (type > -1) {
                    clubJoinedObject.put("isCheck", checkInService.isCheckInToday(user.getUid(), clubJoined.getClubId()));
                } else {
                    clubJoinedObject.put("isCheck", false);
                }
                JSONArray joinedClubs = new JSONArray();
                joinedClubs.add(clubJoinedObject);
                json.put("data", joinedClubs);
            } else if (isMySelf == 0) {
                //如果未加入那就检查是否已申请
                memberApplications = memberService.listMemberApplicationsByUserId(userId);
                if (memberApplications != null && !memberApplications.isEmpty()) {
                    clubApplied = clubService.getClub(memberApplications.get(0).getClubId());
                    JSONObject clubAppliedObject = parseClubJSON(clubApplied, user, sourceAgent);
                    //还在申请中，所以没有权限不需要查了，直接设定
                    clubAppliedObject.put("adminType", AppUtils.STATUS_UNAUDITED);
                    clubAppliedObject.put("memberId", 0);
                    clubAppliedObject.put("isCheck", false);
                    JSONArray clubApplieds = new JSONArray();
                    clubApplieds.add(clubAppliedObject);
                    json.put("applyData", clubApplieds);
                }
            }
        }

        JSONArray recommandArray = new JSONArray();

        //生成推荐列表，如果已加入则不需要出推荐列表
        if (clubJoined == null) {
            List<Long> applyClubIdList = new ArrayList<Long>();
            if (clubApplied != null) {
                applyClubIdList.add(clubApplied.getClubId());
            }

            JSONObject region = WhoisUtil.getProvinceAndCity(ip);
            if (provinceId == 0 && cityId == 0) {
                provinceId = region.get("areaCode").toString().equals("null") ? 0 : region.getIntValue("areaCode");
                cityId = region.get("cityCode").toString().equals("null") ? 0 : region.getIntValue("cityCode");
            }
            long areaId = RegionUtil.getRegionId(provinceId);
            json.put("areaName", provinceId);
            json.put("areaCode", region.get("proCode"));
            json.put("cityName", region.get("city"));
            json.put("cityCode", cityId);
            List<Club> listClub = clubService.listClubByRegion(cityId, 0, 0, recommandListNum, applyClubIdList);

            if (listClub == null || listClub.isEmpty()) {
                //根据省ID查询车友会
                listClub = clubService.listClubByRegion(0, provinceId, 0, recommandListNum, applyClubIdList);
            }
            if (listClub == null || listClub.isEmpty()) {
                //根据地区ID查询数据
                listClub = clubService.listClubByRegion(0, 0, areaId, recommandListNum, applyClubIdList);
            }
            if (listClub == null || listClub.isEmpty()) {
                log.warn("region: {}", region.toString());
                listClub = clubService.listClubByRegion(0, 0, 0, recommandListNum, applyClubIdList);
            }
            for (Club club : listClub) {
                JSONObject jsonObject = parseRecommendClubJSON(club, user, sourceAgent);
                recommandArray.add(jsonObject);
            }
        }
        json.put("recommendData", recommandArray);
        AppUtils.setSuccessCode(json);
        if (StringUtils.isBlank(callback)) {
            resp.getWriter().println(json.toString());
        } else {
            resp.getWriter().println(EncodeUtils.encodeForHTML(callback, 2) + "(" + json.toString() + ")");
        }
    }

    /**
     * 根据用户ID或者地区ID获取车友会列表
     *
     * @throws IOException
     *
     */
    @ResponseBody
    @RequestMapping(value = "/club/getClubByUIdOrRegionIdOld.do", method = RequestMethod.GET)
    public void getClubByUIdOrRegionId(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        WebUtils.setEncoding(req, resp);
        String callback = WebUtils.param(req, "callback", "");
        int isMySelf = WebUtils.paramInt(req, "isMine", 0);
        long provinceId = WebUtils.paramInt(req, "provinceId", 0);
        long cityId = WebUtils.paramInt(req, "cityId", 0);
        long userId = WebUtils.paramLong(req, "userId", 0);
        String ip = WhoisUtil.getIp(req);
        String ips = WebUtils.paramTrim(req, "ip", "");
        int sourceAgent = WebUtils.paramInt(req, "source_agent", 2);
        if (StringUtils.isNotBlank(ips)) {
            ip = ips;
        }
        List<Club> listClub = null;
        int isJoin = 0;//数据类型 0 已经加入车友会，1 审核中车友会，2地区推荐车友会 
        JSONObject json = new JSONObject();
        User user = null;
        if (userId > 0) {
            user = userService.findUser(userId);
        }
        ClubMember clubMember = null;
        if (user != null && user.getUid() > 0) {
            json.put("userId", user.getUid());
            listClub = clubService.listByUserId(user.getUid());
            clubMember = memberService.findClubMemberByUserId(user.getUid());
            isJoin = 1;
        }
        List<Long> idList = new ArrayList<Long>();
        //获取申请审核中的车友会
        List<MemberApplication> memberApplications = null;
        JSONObject array = WhoisUtil.getProvinceAndCity(ip);//intfService.getPlaceByIp(ip); array不会为空
        if (isMySelf == 0 && (listClub == null || listClub.isEmpty()) && user != null && user.getUid() > 0) {
            memberApplications = memberService.listMemberApplicationsByUserId(user.getUid());
            JSONArray applicationArray = new JSONArray();
            if (memberApplications != null && memberApplications.size() > 0) {
                for (MemberApplication m : memberApplications) {
                    Club club = clubService.getClub(m.getClubId());
                    Map<String, Object> map = clubService.getAdminTypeAndIdByMember(null, memberApplications, club);
                    JSONObject jsonObject = parseClubJSON(club, user, sourceAgent);
                    int type = (Integer) map.get("adminType");
                    jsonObject.put("adminType", type);
                    jsonObject.put("memberId", map.get("memberId"));
                    jsonObject.put("isCheck", false);
                    applicationArray.add(jsonObject);
                    idList.add(m.getClubId());
                }
                json.put("applyData", applicationArray);
                isJoin = 2;
            }
        }
        if ((listClub == null || listClub.isEmpty())) {
            if (provinceId == 0 && cityId == 0) {
                provinceId = array.get("areaCode").toString().equals("null") ? 0 : array.getIntValue("areaCode");
                cityId = array.get("cityCode").toString().equals("null") ? 0 : array.getIntValue("cityCode");
            }
            long areaId = RegionUtil.getRegionId(provinceId);
            json.put("areaName", provinceId);
            json.put("areaCode", array.get("areaCode"));
            json.put("cityName", array.get("cityName"));
            json.put("cityCode", cityId);
            listClub = clubService.listClubByRegion(cityId, 0, 0, idList);

            if (listClub == null || listClub.isEmpty()) {
                //根据省ID查询车友会
                listClub = clubService.listClubByRegion(0, provinceId, 0, idList);
            }
            if (listClub == null || listClub.isEmpty()) {
                //根据地区ID查询数据
                listClub = clubService.listClubByRegion(0, 0, areaId, idList);
            }
            if (listClub == null || listClub.isEmpty()) {
                listClub = clubService.listClubByRegion(0, 0, 0, idList);
            }
            isJoin = 3;
        }
        if (isMySelf == 0 && (listClub == null || listClub.isEmpty())) {
            listClub = clubService.listClubByRegion(0, 0, 0, idList);
        }
        if (listClub != null && !listClub.isEmpty()) {
            JSONArray jsonArray = new JSONArray();
            for (Club club : listClub) {
                JSONObject jsonObject = parseClubJSON(club, user, sourceAgent);
                if (isJoin == 1) {
                    Map<String, Object> map = clubService.getAdminTypeAndIdByMember(clubMember, memberApplications, club);
                    int type = (Integer) map.get("adminType");
                    jsonObject.put("adminType", type);
                    jsonObject.put("memberId", map.get("memberId"));
                    if (type > -1) {
                        jsonObject.put("isCheck", checkInService.isCheckInToday(user.getUid(), club.getClubId()));
                    } else {
                        jsonObject.put("isCheck", false);
                    }
                } else {
                    jsonObject.put("adminType", -1);
                    jsonObject.put("isCheck", false);
                    jsonObject.put("memberId", 0);
                }
                jsonArray.add(jsonObject);
            }
            if (isJoin == 1) {
                json.put("data", jsonArray);
            } else if (isJoin == 3) {
                json.put("recommendData", jsonArray);
            }
            AppUtils.setSuccessCode(json);
        } else {
            json.put("recommendData", new JSONArray());
            AppUtils.setSuccessCode(json);
        }
        if (StringUtils.isBlank(callback)) {
            resp.getWriter().println(json.toString());
        } else {
            resp.getWriter().println(EncodeUtils.encodeForHTML(callback, 2) + "(" + json.toString() + ")");
        }
    }

    /**
     *
     * 获取车友会列表接口(APP)
     *
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "/club/getClubByCityOrRegionId.do", method = RequestMethod.GET)
    public void getClubByCityOrRegionId(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        WebUtils.setEncoding(req, resp);
        // app签到用这个接口判断，app的调用不能加缓存
        if (!"utf-8".equalsIgnoreCase(req.getParameter("resp_enc"))) {
            WebUtils.setCacheHeader(resp, 3600);//缓存 1h
        }
        String callback = WebUtils.param(req, "callback", "");
        long cityId = WebUtils.paramInt(req, "cityId", 0);
        long provinceId = WebUtils.paramInt(req, "provinceId", 0);
        long seriesId = WebUtils.paramInt(req, "seriesId", 0);
        String[] seriesIds = WebUtils.paramTrim(req, "seriesIds", "").split(",");
        String clubName = WebUtils.paramTrim(req, "clubName", "");
        long clubId = WebUtils.paramLong(req, "clubId", 0);
        long userId = WebUtils.paramLong(req, "userId", 0);
        long brandId = WebUtils.paramInt(req, "brand", 0);
        int pageNo = WebUtils.paramInt(req, "pageNo", 1);
        int pageSize = WebUtils.paramInt(req, "pageSize", 20, MIN_PAGESIZE, MAX_PAGESIZE);
        int sourceAgent = WebUtils.paramInt(req, "source_agent", 2);
        int tabId = WebUtils.paramInt(req, "tagId", 0);//主题ID
        User user = null;
        if (userId > 0) {
            user = userService.findUser(userId);
        }
        ClubMember clubMember = null;
        List<MemberApplication> memberApplications = null;
        if (user != null) {
            clubMember = memberService.findClubMemberByUserId(user.getUid());
            memberApplications = memberService.listMemberApplicationsByUserId(user.getUid());
        }
        List<Object> sids = new ArrayList<Object>(seriesIds.length);
        if (seriesId > 0) {
            sids.add(seriesId);
        } else {
            for (String s : seriesIds) {
                try {
                    int i = Integer.parseInt(s);
                    if (i > 0) {
                        sids.add(i);
                    }
                } catch (java.lang.NumberFormatException e) {
                    continue;
                }
            }
        }
        Pager<Club> pager = clubService.pageClubByPlaceId(cityId, 0, provinceId, brandId, sids.toArray(), clubId, clubName, pageNo, pageSize, tabId);
        JSONObject json = new JSONObject();
        if (pager.getResultList() != null && !pager.getResultList().isEmpty()) {
            JSONArray jsonArray = new JSONArray();
            for (Club club : pager.getResultList()) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("clubId", club.getClubId());
                jsonObject.put("name", EncodeUtils.encodeForHTML(club.getName(), sourceAgent));
                jsonObject.put("logo", EncodeUtils.encodeForHTML(club.getLogo(), sourceAgent));
                jsonObject.put("memberSum", club.getMemberNum());
                jsonObject.put("vipSum", club.getVipNum());
                jsonObject.put("totalPetrol", club.getTotalPetrol());
                jsonObject.put("level", club.getLevelId());
                ClubLevel clubLevel = clubLevelService.getById(club.getLevelId());
                jsonObject.put("levelName", EncodeUtils.encodeForHTML(clubLevel == null ? "" : clubLevel.getLevelName(), sourceAgent));
                String activityName = "";
                List<Activity> listActivity = activityService.getNewActivity(club.getClubId(), 1);
                if (listActivity != null && !listActivity.isEmpty()) {
                    Activity activity = listActivity.get(0);
                    activityName = activity.getTitle();
                }
                jsonObject.put("clubStatus", club.getStatus());
                jsonObject.put("isLeastLevel", clubLevelService.isLeast(club.getLevelId()));
                jsonObject.put("brandId", club.getBrandId());
                jsonObject.put("activityName", EncodeUtils.encodeForHTML(activityName, sourceAgent));
                //留言总数,现在的版本已经没有留言
                jsonObject.put("commentSum", club.getReplyNum());
                jsonObject.put("rank", club.getRank());
                jsonObject.put("regionRank", club.getRegionRank());
                jsonObject.put("provinceRank", club.getProvinceRank());
                jsonObject.put("brandRank", club.getBrandRank());
                jsonObject.put("albumSum", albumService.countAlbumByClubId(club.getClubId()));
                jsonObject.put("photoSum", albumService.countPhotoByClubId(club.getClubId()));
                jsonObject.put("topicSum", topicService.countByClubId(club.getClubId()));
                jsonObject.put("activitySum", activityService.countActivityByClubId(club.getClubId()));
                jsonObject.put("seriesName", EncodeUtils.encodeForHTML(club.getSeriesName(), sourceAgent));
                jsonObject.put("brandName", EncodeUtils.encodeForHTML(club.getBrandName(), sourceAgent));
                jsonObject.put("provinceName", EncodeUtils.encodeForHTML(club.getProvinceName(), sourceAgent));
                jsonObject.put("cityName", EncodeUtils.encodeForHTML(club.getCityName(), sourceAgent));
                jsonObject.put("introduce", EncodeUtils.encodeForHTML(club.getIntroduce(), sourceAgent));
                jsonObject.put("qqGroup", club.getQqGroup());
                jsonObject.put("announcement", EncodeUtils.encodeForHTML(clubService.getNotice(club.getClubId()).getContent(), sourceAgent));
                jsonObject.put("clubUrl", club.getClubUrl());
                jsonObject.put("forumId", clubService.getFirstFormum(club.getClubId()));
                Map<String, Object> map = clubService.getAdminTypeAndIdByMember(clubMember, memberApplications, club);
                int type = (Integer) map.get("adminType");
                jsonObject.put("adminType", type);
                jsonObject.put("memberId", map.get("memberId"));
                if (type > -1) {
                    jsonObject.put("isCheck", checkInService.isCheckInToday(userId, clubId));
                } else {
                    jsonObject.put("isCheck", false);
                }
                //主题URL
                jsonObject.put("clubBackgroundImg", club.getAppBanner() == null ? "" : club.getAppBanner());
                //判断是否有升级提示
                boolean isTopLevel = clubLevelService.isHighest(club.getLevelId());
                long nextNeedPetrol = 0;
                long nextNeedVip = 0;
                if (!isTopLevel) {
                    ClubLevel clubNextLevel = clubLevelService.getNextLevel(club.getLevelId());
                    if (clubNextLevel != null) {
                        long nextLevelId = clubNextLevel.getLevelId();
                        nextNeedPetrol = clubLevelService.getNextLevelNeedPetrol(nextLevelId, (int) club.getTotalPetrol());
                        nextNeedVip = clubLevelService.getNextLevelNeedMember(nextLevelId, (int) club.getVipNum());
                    }
                }
                if (!isTopLevel && nextNeedVip < 1 && nextNeedPetrol < 1) {
                    jsonObject.put("levelupTip", 1);//提示可升级
                } else {
                    jsonObject.put("levelupTip", 0);//提示不可升级
                }
                //获取等待审核加入车友会申请数量
                try {
                    int applyCount = memberService.countMemberApplication(club.getClubId());
                    jsonObject.put("applyCount", applyCount);
                } catch (EmptyResultDataAccessException e) {
                    log.error("无法获取待审加入车友会成员信息clubId=" + club.getClubId());
                }
                //会长昵称
                try {
                    ClubMember adminClubMember = memberService.findAdminByClubId(club.getClubId());
                    jsonObject.put("presidentName", userService.getNickNameByUserId(adminClubMember.getUid()));
                } catch (Exception e) {
                    log.error("无法获取车友会长信息clubId=" + club.getClubId());
                }

                jsonArray.add(jsonObject);
            }
            AppUtils.setSuccessCode(json);
            json.put("data", jsonArray);
            json.put("total", pager.getTotal());
            json.put("pageNo", pager.getPageNo());
            json.put("pageCount", pager.getPageCount());
            json.put("pageSize", pager.getPageSize());
        } else {
            json.put("data", new JSONArray());
            AppUtils.setSuccessCode(json);
        }

        try {
            PrintWriter print = resp.getWriter();
            if (StringUtils.isNotBlank(callback)) {
                print.println(EncodeUtils.encodeForHTML(callback, 2) + "(" + json.toJSONString() + ")");
            } else {
                print.println(json.toJSONString());
            }
            print.flush();
            print.close();
        } catch (IOException ex) {
            log.error("error", ex);
        }

    }

    /**
     * 获取车友会列表接口 给个人中心调用
     *
     * @throws
     */
    @ResponseBody
    @RequestMapping(value = "/club/getClubListByCityId.do", method = RequestMethod.GET)
    public void getClubListByCityId(HttpServletRequest req, HttpServletResponse resp) {
        long cityId = WebUtils.paramInt(req, "cityId", 0);
        long provinceId = WebUtils.paramInt(req, "provinceId", 0);
        String callback = WebUtils.param(req, "callback", "");
        int pageNo = WebUtils.paramInt(req, "pageNo", 1);
        int pageSize = WebUtils.paramInt(req, "pageSize", 20, MIN_PAGESIZE, MAX_PAGESIZE);
        int sourceAgent = WebUtils.paramInt(req, "source_agent", DEF_SOURCE_AGENT);
        try {
            //  WebUtils.setEncoding(req, resp);
            req.setCharacterEncoding("GBK");
            resp.setCharacterEncoding("GBK");


        } catch (UnsupportedEncodingException ex) {
            log.error("error", ex);
        }
        Pager<Club> pager = clubService.listClubByCityId(cityId, provinceId, pageNo, pageSize);
        JSONObject json = new JSONObject();
        if (pager.getTotal() == 0) {
            if (cityId != 0) { // 当地区ID不为0时
                if (provinceId != 0) {
                    pager = clubService.listClubByCityId(0, provinceId, pageNo, pageSize); //根据省份
                    if (pager.getTotal() == 0) {
                        pager = clubService.listClubByCityId(0, 0, pageNo, pageSize);//根据全国
                        json.put("type", "nation");
                    } else {
                        json.put("type", "province");
                    }
                } else {
                    pager = clubService.listClubByCityId(0, 0, pageNo, pageSize);//省份ID为0根据全国查
                    json.put("type", "nation");
                }

            } else { //地区ID为0时
                if (provinceId != 0) {
                    pager = clubService.listClubByCityId(0, 0, pageNo, pageSize);//根据全国查
                    json.put("type", "nation");
                }
            }
        } else {
            json.put("type", "city");
        }

        if (pager.getResultList() != null && !pager.getResultList().isEmpty()) {
            JSONArray jsonArray = new JSONArray();
            for (Club club : pager.getResultList()) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("clubId", club.getClubId());
                jsonObject.put("name", EncodeUtils.encodeForHTML(club.getName(), sourceAgent));
                jsonObject.put("logo", EncodeUtils.encodeForHTML(club.getLogo(), sourceAgent));
                jsonObject.put("memberSum", club.getMemberNum());
                jsonObject.put("clubUrl", club.getClubUrl());
                jsonObject.put("totalPetrol", petrolService.getValidPetrol(club.getClubId()).getTotalPetrol());
                jsonObject.put("level", club.getLevelId());
                jsonObject.put("levelName", EncodeUtils.encodeForHTML(clubLevelService.getById(club.getLevelId()).getLevelName(), sourceAgent));
                String activityName = "";
                List<Activity> listActivity = activityService.getNewActivity(club.getClubId(), 1);
                if (listActivity != null && !listActivity.isEmpty()) {
                    Activity activity = listActivity.get(0);
                    activityName = activity.getTitle();
                }
                jsonObject.put("activityName", EncodeUtils.encodeForHTML(activityName, sourceAgent));
                jsonObject.put("commentSum", commentService.countByClubId(club.getClubId()));
                jsonObject.put("rank", club.getRank());
                jsonObject.put("brandRank", club.getBrandRank());
                jsonObject.put("provinceRank", club.getProvinceRank());
                jsonObject.put("regionRank", club.getRegionRank());
                jsonObject.put("albumSum", albumService.countAlbumByClubId(club.getClubId()));
                jsonObject.put("photoSum", albumService.countPhotoByClubId(club.getClubId()));
                jsonObject.put("topicSum", topicService.countByClubId(club.getClubId()));
                jsonObject.put("activitySum", activityService.countActivityByClubId(club.getClubId()));
                jsonObject.put("seriesName", EncodeUtils.encodeForHTML(club.getSeriesName(), sourceAgent));
                jsonObject.put("brandName", EncodeUtils.encodeForHTML(club.getBrandName(), sourceAgent));
                jsonObject.put("provinceName", EncodeUtils.encodeForHTML(club.getProvinceName(), sourceAgent));
                jsonObject.put("cityName", EncodeUtils.encodeForHTML(club.getCityName(), sourceAgent));
                jsonObject.put("introduce", EncodeUtils.encodeForHTML(club.getIntroduce(), sourceAgent));
                jsonObject.put("qqGroup", club.getQqGroup());
                jsonObject.put("announcement", EncodeUtils.encodeForHTML(clubService.getNotice(club.getClubId()).getContent(), sourceAgent));
                jsonArray.add(jsonObject);
            }
            json.put("data", jsonArray);

        } else {
            json.put("data", new JSONArray());
        }
        json.put("total", pager.getTotal());
        json.put("pageCount", pager.getPageCount());
        json.put("pageNo", pager.getPageNo());
        json.put("pageSize", pager.getPageSize());
        PrintWriter print = null;
        try {
            print = resp.getWriter();
            if (StringUtils.isNotBlank(callback)) {
                print.println(EncodeUtils.encodeForHTML(callback, DEF_SOURCE_AGENT) + "(" + json.toJSONString().replaceAll("<", "&lt;").replaceAll(">", "&gt;") + ")");
            } else {
                print.println(json.toJSONString().replaceAll("<", "&lt;").replaceAll(">", "&gt;"));


            }
        } catch (IOException ex) {
            log.error("error", ex);
        }
        print.flush();
        print.close();
    }

    /**
     * 修改车友会信息接口 editType: 1》会标修改，2》宣言(简介)修改，3》公告修改,4》顶部背景
     *
     * @throws
     */
    @ResponseBody
    @RequestMapping(value = "/club/editClub.do", method = RequestMethod.POST)
    public JSONObject editClub(HttpServletRequest req, HttpServletResponse resp) {
        WebUtils.setEncoding(req, resp);
        long clubId = WebUtils.paramLong(req, "clubId", 0);
        int editType = WebUtils.paramInt(req, "editType", 0);
        String content = WebUtils.param(req, "content", "");
        JSONObject json = new JSONObject();
        User user = userAuth.getUser(req, resp);
        int code;
        String message = "";

        if (user != null && user.getUid() > 0) {
            if (memberService.isClubNormalAdmin(user.getUid(), clubId)) {
                Club club = clubService.getValidClub(clubId);
                if (club != null) {
                    long i;
                    if (editType == 1) {
                        if (StringUtils.isNotBlank(content)) {
                            club.setLogo(content);
                            i = clubService.update(club);
                        } else {
                            i = 3;
                            message = "上传logo不允许为空！";
                        }
                    } else if (editType == 2) {
                        if (content.length() > 45) {
                            i = 3;
                            message = "简介长度不能超过45！";
                        } else {
                            club.setIntroduce(content);
                            i = clubService.update(club);
                        }
                    } else if (editType == 3) {
                        if (StringUtil.length(content) > 100) {
                            i = 3;
                            message = "最多50个汉字或100个字符（字母、数字）！";
                        } else {
                            ClubNotice notice = clubService.getNotice(club.getClubId());
                            if (!notice.getContent().equals(content)) {
                                clubService.saveNotice(club.getClubId(), content, user.getUid());
                                //更新完发动态
                                AbstractDyna d = new AbstractDyna();
                                d.setClubId(club.getClubId());
                                d.setContent(content);
                                d.setTargetId(club.getClubId());
                                d.setCreateBy(user.getUid());
                                d.setCreateName(user.getNickname());
                                d.setCreateDate(notice.getUpdateAt());
                                long dynaInfoId = dynaService.createNoticeDyna(d, null);
                                //发审核
                                censorNoticeService.notifyCensorSystemCreate(req, notice, dynaInfoId);
                            }

                            i = 1;
                        }
                    } else if (editType == 4) {//修改背景URL
                        if (StringUtils.isBlank(content)) {
                            i = 3;
                            message = "背景URL不允许为空！";
                        } else if (StringUtil.length(content) > 255) {
                            i = 3;
                            message = "最多255个字符！";
                        } else {
                            club.setAppBanner(content);
                            long update = clubService.update(club);
                            if (update > 0) {
                                i = 1;
                            } else {
                                i = 3;
                                message = "更新背景URL失败！";
                            }
                        }
                    } else {
                        i = 3;
                        message = "非法参数editType";
                    }
                    //结果处理
                    if (i == 1) {
                        code = 0;
                        message = "修改成功";
                    } else if (i == 3) {
                        code = AppUtils.STATUS_FAIL;
                    } else {
                        code = AppUtils.STATUS_FAIL;
                        message = "修改失败";
                    }
                } else {
                    code = AppUtils.STATUS_DATA_ERROR;
                    message = "该车友会ID不存在";
                }
            } else {
                code = AppUtils.STATUS_PERMISSIONS_ERROR;
                message = "您不是该车友会管理员，只有管理员才能进行该操作哦！";
            }
        } else {
            code = AppUtils.STATUS_NOLOGIN_ERROR;
            message = "您还没有登录";
        }
        json.put("code", code);
        json.put("message", message);
        return json;
    }

    /**
     * 获取论坛相关车友会接口
     *
     * @throws
     */
    @ResponseBody
    @RequestMapping(value = "/club/listClubByForumId.do", method = RequestMethod.GET)
    public JSONObject listClubByForumId(HttpServletRequest req, HttpServletResponse resp) {
        WebUtils.setEncoding(req, resp);
        long forumId = WebUtils.paramLong(req, "forumId", 0);
        long userId = WebUtils.paramLong(req, "userId", 0);
        User user = userService.findUser(userId);
        int pageNo = WebUtils.paramInt(req, "pageNo", 1);
        int pageSize = WebUtils.paramInt(req, "pageSize", 20, MIN_PAGESIZE, MAX_PAGESIZE);
        int sourceAgent = WebUtils.paramInt(req, "source_agent", DEF_SOURCE_AGENT);
        Pager<Club> pager = clubService.pagerClubByForumId(forumId, pageNo, pageSize);
        JSONObject json = new JSONObject();
        if (pager.getResultList() != null && !pager.getResultList().isEmpty()) {
            json.put("total", pager.getTotal());
            json.put("pageNo", pager.getPageNo());
            json.put("pageSize", pager.getPageSize());
            JSONArray jsonArray = new JSONArray();
            ClubMember clubMember = null;
            List<MemberApplication> memberApplications = null;
            if (user != null && user.getUid() > 0) {
                clubMember = memberService.findClubMemberByUserId(user.getUid());
                memberApplications = memberService.listMemberApplicationsByUserId(userId);
            }
            for (Club club : pager.getResultList()) {
                JSONObject jsonObject = clubService.setTopClub2Json(club, sourceAgent);
                Map<String, Object> map = clubService.getAdminTypeAndIdByMember(clubMember, memberApplications, club);
                int type = (Integer) map.get("adminType");
                jsonObject.put("adminType", type);
                if (type > -1) {
                    jsonObject.put("isCheck", checkInService.isCheckInToday(user.getUid(), club.getClubId()));
                } else {
                    jsonObject.put("isCheck", false);
                }
                jsonArray.add(jsonObject);
            }
            json.put("data", jsonArray);
        } else {
            json.put("message", "无数据");
        }

        return json;
    }

    /**
     * 根据论坛ID获取车友会个数
     *
     * @throws
     */
    @ResponseBody
    @RequestMapping(value = "/club/countClubByForumId.do", method = RequestMethod.GET)
    public JSONObject countClubByForumId(HttpServletRequest req, HttpServletResponse resp) {
        WebUtils.setEncoding(req, resp);
        long forumId = WebUtils.paramLong(req, "forumId", 0);
        JSONObject json = new JSONObject();
        json.put("forumId", forumId);
        json.put("total", clubService.countClubByForumId(forumId));
        AppUtils.setSuccessCode(json);
        return json;
    }

    /**
     * 申请创建车友会（登录用户即可）(APP共用，code暂用PC端)
     *
     * @param request
     * @param model
     * @param resp
     * @throws
     * @
     */
    @ResponseBody
    @RequestMapping(value = "/club/createClub.do", method = RequestMethod.POST)
    public JSONObject createClub(HttpServletRequest req, HttpServletResponse resp) {
        WebUtils.setEncoding(req, resp);
        User user = userAuth.getUser(req, resp);
        JSONObject json = new JSONObject();
        int code = -1;
        String message = "创建失败";
        if (user != null && user.getUid() > 0) {
            Club club = this.reqConvert2Club(req, user.getUid());
            ClubAddress address = this.reqConvert2Address(req, user.getUid());

            String retMsg = this.checkClubForm(club, address, req, user);
            if ("true".equals(retMsg)) {
                long clubId = clubService.create(club, address);
                //验证通过，绑定手机
                JSONObject bindPhone = intfService.bindPhone(address.getPhone(), WebUtils.paramTrim(req, "code", ""),
                        WebUtils.cookie(req, systemConfig.getUserSessionName()));
                //绑定通过更新用户状态
                if (bindPhone != null && bindPhone.getIntValue("code") == 0) {
                    user.setPhone(address.getPhone());
                    user.setIsSyncdPhone(User.IS_SYNC_PHONE);
                    userService.updateUser(user);
                }
                if (clubId > 0) {
                    code = 0;
                    message = "创建成功";
                    //第一次创建简介，通知审核平台
                    censorIntroduceService.notifyCensorSystemCreate(req, club);
                    if (user.isComplete() == false) {
                        //同步用户信息
                        user.setTruename(address.getName());
                        user.setProvinceId(address.getProvinceId());
                        user.setProvince(address.getProvinceName());
                        user.setPhone(address.getPhone());
                        user.setPhoneValidated(1);
                        user.setCityId(address.getCityId());
                        user.setCity(address.getCityName());
                    }
                    user.setGender(WebUtils.paramInt(req, "gender", -1));
                    user.setBirthday(WebUtils.parseDate(req, "birthday"));
                    userService.updateUser(user);
                }
            } else {
                code = AppUtils.STATUS_DATA_ERROR;
                message = retMsg;
            }
        } else {
            code = AppUtils.STATUS_NOLOGIN_ERROR;
            message = "用户未登录";
        }
        json.put("code", code);
        json.put("message", message);
        return json;
    }

    /**
     * 表单转车友会对象
     *
     * @param req
     * @return
     */
    public Club reqConvert2Club(HttpServletRequest req, long userId) {
        Club club = new Club();
        Date currentDate = DateUtils.getNow();
        club.setAdminId(userId);
        club.setAuditAt(null);
        club.setAuditBy(0);
        long brandId = WebUtils.paramLong(req, "brandId", 0);
        club.setBrandId(brandId);
        String brandName = WebUtils.getAreaPlaceByReq(req, "brandName", "");
        club.setBrandName(brandName);
        long cityId = WebUtils.paramLong(req, "cityId", 0);
        club.setCityId(cityId);
        String cityName = WebUtils.getAreaPlaceByReq(req, "cityName", "");
        club.setCityName(cityName);
        club.setCreateAt(currentDate);
        club.setCreateBy(userId);
        club.setIntroduce(WebUtils.param(req, "introduce", ""));
        club.setLevelId(0);
        club.setLogo("");
        club.setMemberNum(0);
        club.setName(WebUtils.paramTrim(req, "clubName", ""));
        long provinceId = WebUtils.paramLong(req, "provinceId", 0);
        long regionId = RegionUtil.getRegionId(provinceId);
        club.setProvinceId(provinceId);
        String provinceName = WebUtils.paramTrim(req, "provinceName", "");
        club.setProvinceName(provinceName);
        club.setRegionId(regionId);
        club.setRegionName(RegionUtil.getRegionName(regionId));
        club.setReplyNum(0);
        long seriesId = WebUtils.paramLong(req, "seriesId", 0);
        club.setSeriesId(seriesId);
        String seriesName = WebUtils.paramTrim(req, "seriesName", "");
        club.setSeriesName(seriesName);
        club.setStatus(Club.STATUS_UNAUDITED);
        club.setTopicNum(0);
        club.setUpdateAt(currentDate);
        club.setUpdateBy(userId);
        club.setQqGroup(WebUtils.paramTrim(req, "qqGroup", ""));
        club.setVipNum(0);
        club.setClubUrl(WebUtils.paramTrim(req, "clubUrl", "").replaceAll(" ", "").toLowerCase());
        club.setType(WebUtils.paramInt(req, "type", 0));//车友会类型 1:地区车友；2：车系车友；3：主题车友
        club.setThemeId(WebUtils.paramLong(req, "themeId", 0L));//主题类型
        club.setAppBanner(WebUtils.param(req, "appBanner", ""));//车友会背景URL

        //type=0兼容旧版本参数检查
        if (club.getType() == 0) {
            if (brandId != 0 && StringUtils.isNotBlank(brandName) && seriesId != 0 && StringUtils.isNotBlank(seriesName)) {
                club.setType(Club.TYPE_SERIAL);//如果车系数据不为空，就把此车友会归纳为品牌、车系车友会
            } else if (provinceId != 0 && StringUtils.isNotBlank(provinceName) && cityId != 0 && StringUtils.isNotBlank(cityName)) {
                club.setType(Club.TYPE_AREA);//如果车系参数不全，地区参数全，就把此车友会归纳为地区车友会
            }
        }
        return club;
    }

    /**
     * 表单转车友会地址对象
     *
     * @param req
     * @return
     */
    public ClubAddress reqConvert2Address(HttpServletRequest req, long userId) {
        ClubAddress clubAddress = new ClubAddress();
        clubAddress.setAddress(WebUtils.paramTrim(req, "address", ""));
        clubAddress.setCityId(WebUtils.paramInt(req, "clubAddressCityId", 0));
        clubAddress.setCityName(WebUtils.getAreaPlaceByReq(req, "clubAddressCityName", ""));
        clubAddress.setName(WebUtils.paramTrim(req, "realName", ""));
        clubAddress.setPhone(WebUtils.paramTrim(req, "phone", ""));
        clubAddress.setPostcode(WebUtils.paramTrim(req, "postCode", ""));
        clubAddress.setProvinceId(WebUtils.paramInt(req, "clubAddressProvinceId", 0));
        clubAddress.setProvinceName(WebUtils.paramTrim(req, "clubAddressProvinceName", ""));
        clubAddress.setUpdateAt(DateUtils.getNow());
        clubAddress.setUpdateBy(userId);
        return clubAddress;
    }

    /**
     * 验证申请车友会信息
     *
     * @param club
     * @param req
     * @param req
     * @param user
     * @return
     */
    public String checkClubForm(Club club, ClubAddress clubAddress, HttpServletRequest req, User user) {
        String name = club.getName();
        String retNameMsg = clubService.checkClubName(name);
        if (!"true".equals(retNameMsg)) {
            return retNameMsg;
        }
        String clubUrl = club.getClubUrl();
        String retMsg = clubService.checkClubUrl(clubUrl);
        if (!"true".equals(retMsg)) {
            return retMsg;
        }

        long provinceId = club.getProvinceId();
        String provinceName = club.getProvinceName();
        long cityId = club.getCityId();
        String cityName = club.getCityName();
        long brandId = club.getBrandId();
        String brandName = club.getBrandName();
        long seriesId = club.getSeriesId();
        String seriesName = club.getSeriesName();
        int type = club.getType();
        long themeId = club.getThemeId();

        if (type == 0) {//代码参数有误
            return "非法参数provinceId|provinceName|cityId|cityName|brandId|brandName|seriesId|seriesName";
        } else if (type == 1) {//如果type=1,创建地区车友会；
            if (provinceId != 0 && StringUtils.isBlank(provinceName)) {
                return "缺少省份名称";
            } else if (provinceName.length() > INPUT_MAX_LENGTH) {
                return "非法省份名称";
            }
            if (cityId != 0 && StringUtils.isBlank(cityName)) {
                return "缺少城市名称";
            } else if (cityName.length() > INPUT_MAX_LENGTH) {
                return "非法城市名称";
            }
        } else if (type == 2) {//如果type=2,创建品牌/车系车友会；
            if (brandId != 0 && StringUtils.isBlank(brandName)) {
                return "缺少品牌名称";
            } else if (brandName.length() > INPUT_MAX_LENGTH) {
                return "非法品牌名称";
            }

            if (seriesId != 0 && StringUtils.isBlank(seriesName)) {
                return "缺少车系名称";
            } else if (seriesName.length() > INPUT_MAX_LENGTH) {
                return "非法车系名称";
            }
        } else if (type == 3) {//如果type=3,创建主题车友会；
            Theme theme = themeService.findThemeById(themeId);
            if (theme == null) {
                return "非法参数themeId";
            }
        } else {
            return "非法参数type";
        }

        if (provinceId == 0 && cityId != 0) {//非法操作
            return "缺少省份";
        }
        if (brandId == 0 && seriesId != 0) {//非法操作
            return "缺少车型";
        }

        //验证车友会地址
        String realName = clubAddress.getName();
        if (StringUtils.isBlank(realName)) {
            return "请输入姓名";
        } else if (realName.length() > INPUT_MAX_LENGTH) {
            return "姓名过长";
        }

        //新版本不需要填写省市，详细地址，邮编，出生日期
        //为了兼容新旧版本，所以不做检查，由APP调用前进行检查
        /*
         long clubAddressCityId = clubAddress.getCityId();
         long clubAddressProvinceId = clubAddress.getProvinceId();
         String clubAddressProvinceName = clubAddress.getProvinceName();
         String clubAddressCityName = clubAddress.getCityName();
         if (clubAddressCityId == 0 || clubAddressProvinceId == 0
         || StringUtils.isBlank(clubAddressProvinceName) || StringUtils.isBlank(clubAddressCityName)) {
         return "请选择所在地区";
         }
         String address = clubAddress.getAddress();
         if (StringUtils.isBlank(address)) {
         return "请填写详细地址";
         } else if (address.length() > DB_MAX_LENGTH) {
         return "详细地址过长";
         }
         String postcode = clubAddress.getPostcode();
         if (StringUtils.isBlank(postcode)) {
         return "请填写邮编";
         }
         if (!postcode.matches(Regex.postcode.value)) {
         return "请填写合法的邮编";
         }
         String birthdayStr = WebUtils.paramTrim(req, "birthday", "");
         if (StringUtils.isBlank(birthdayStr)) {
         return "请选择出生日期";
         }
         Date birthday = WebUtils.parseDate(req, "birthday");
         if (birthday == null) {
         return "请选择合法的出生日期";
         }
         */
        String phone = clubAddress.getPhone();
        String retPhoneMsg = clubService.checkClubPhone(phone);
        if (!"true".equals(retPhoneMsg)) {
            return retPhoneMsg;
        }
        int gender = WebUtils.paramInt(req, "gender", -1);
        if (gender == -1) {
            return "请选择性别";
        }
        String checkcode = WebUtils.paramTrim(req, "code", "");
        if (StringUtils.isBlank(checkcode)) {
            return "请输入验证码";
        }
        if (systemConfig.isNeedCheckCode()) {
            String checkCodeMsg = checkPhoneCode(phone, checkcode);
            if (StringUtils.isNotEmpty(checkCodeMsg)) {
                return checkCodeMsg;
            }
        }

        int agree = WebUtils.paramInt(req, "agree", -1);
        if (agree == -1) {
            return "请阅读并同意《中国车友会管理条例》";
        }
        String tip = clubService.checkJoinedClub(user);
        if (StringUtils.isNotEmpty(tip)) {
            return tip;
        }
        return "true";
    }

    /**
     * 上个自然周 新增认证人数|新增油值 top10排行 给 大首页-论坛版块-周认证榜、加油榜 调用
     *
     * @param req
     * @param resp
     * @return
     * @throws
     * @deprecated 这个接口作废，已经有新接口替换 listTopForSeries listTopForRegion listTopByPetrol listTopByRank
     */
    @ResponseBody
    @RequestMapping(value = "/club/listTopClubWeekly.do", method = RequestMethod.GET)
    public void listTopClubWeekly(HttpServletRequest req, HttpServletResponse resp) {
        WebUtils.setCacheHeader(resp, 1800);//缓存半小时
        WebUtils.setEncoding(req, resp);
        String callback = WebUtils.param(req, "callback", "");
        JSONObject json = new JSONObject();
        JSONArray arr = new JSONArray();
        JSONArray arrIndex = new JSONArray();//用于保存本车友会排名前后2名的信息
        int rank = 0;
        int brandRank = 0;
        int provinceRank = 0;
        long regionId = 0L;
        long brandIdByClub = 0L;
        long provinceIdByClub = 0L;
        int type = WebUtils.paramInt(req, "type", 0);
        int source = WebUtils.paramInt(req, "source", 1);
        int sourceAgent = WebUtils.paramInt(req, "source_agent", DEF_SOURCE_AGENT);
        long userId = WebUtils.paramLong(req, "userId", 0);
        long cityId = WebUtils.paramInt(req, "cityId", 0);
        long provinceId = WebUtils.paramInt(req, "provinceId", 0);
        long seriesId = WebUtils.paramInt(req, "seriesId", 0);
        long brandId = WebUtils.paramInt(req, "brand", 0);
        //是否需要返回后面数组，用于首页排行榜是否有变化显示，0则返回，1只返回排名变化
        int showType = WebUtils.paramInt(req, "showType", 0);
        User user = userService.findUser(userId);
        if (source == 2) {
            json.put("dataStart", DateUtils.format(DateUtils.getLastWeekStart()).replaceAll("-", "."));
            json.put("dataEnd", DateUtils.format(DateUtils.getLastWeekEnd()).replaceAll("-", "."));
        } else {
            json.put("dataStart", DateUtils.getLastWeekStart());
            json.put("dataEnd", DateUtils.getLastWeekEnd());
        }
        ClubMember clubMember = null;
        List<MemberApplication> memberApplications = null;
        if (user != null && user.getUid() > 0) {
            clubMember = memberService.findClubMemberByUserId(user.getUid());
            memberApplications = memberService.listMemberApplicationsByUserId(user.getUid());
            // 如果此用户已经加入车友会,返回车友会全国，车系，地区排名
            try {
                if (clubMember != null) {
                    Club club = clubService.getClub(clubMember.getClubId());
                    if (club != null) {
                        rank = club.getRank();
                        int dayRank = club.getDayRank();
                        brandRank = club.getBrandRank();
                        int dayBrandRank = club.getDayBrandRank();
                        provinceRank = club.getProvinceRank();
                        int dayProvinceRank = club.getDayProvinceRank();
                        regionId = club.getRegionId();
                        brandIdByClub = club.getBrandId();
                        provinceIdByClub = club.getProvinceId();
                        json.put("rank", rank);
                        //如果昨天的全国排名为0，不参与排名升降比较
                        json.put("rankAsc", dayRank == 0 ? 0 : dayRank - rank);
                        json.put("brandRank", brandRank);
                        //如果昨天的品牌排名为0，不参与排名升降比较
                        json.put("brandRankAsc", dayBrandRank == 0 ? 0 : dayBrandRank - brandRank);
                        json.put("provinceRank", provinceRank);
                        //如果昨天的地区排名为0，不参与排名升降比较
                        json.put("provinceRankAsc", dayProvinceRank == 0 ? 0 : dayProvinceRank - provinceRank);
                    }
                }
            } catch (DataAccessException e) {
                log.error("throw exception [memberService.findClubMemberByUserId], userId=" + userId, e);
            }
        }

        //type=0,1是之前的逻辑，不应该受到showType的影响
        if (type == 0) {
            List<ClubTotalMember> list = statService
                    .listClubMemberNumWeekly(10, 1);
            for (ClubTotalMember ctm : list) {
                Club c = clubService.getClub(ctm.getClubId());
                JSONObject obj = clubService
                        .setTopClub2Json(c, sourceAgent);
                obj.put("weekVipNum",
                        ctm.getWeekVipTotal() - ctm.getLastWeekVipTotal());
                Map<String, Object> map = clubService.getAdminTypeAndIdByMember(clubMember,
                        memberApplications, c);
                int adminType = (Integer) map.get("adminType");
                obj.put("adminType", adminType);
                if (adminType > -1) {
                    obj.put("isCheck",
                            checkInService.isCheckInToday(user.getUid(),
                            c.getClubId()));
                } else {
                    obj.put("isCheck", false);
                }
                arr.add(obj);
            }
            json.put("data", arr);
        } else if (type == 1) {
            List<ClubStat> list = statService.getClubWeekPetrolTop(10,
                    provinceId, cityId, brandId, seriesId);
            for (ClubStat cs : list) {
                Club c = clubService.getClub(cs.getClubId());
                JSONObject obj = clubService
                        .setTopClub2Json(c, sourceAgent);
                obj.put("weekPetrol", cs.getWeekPetrol());
                Map<String, Object> map = clubService.getAdminTypeAndIdByMember(clubMember,
                        memberApplications, c);
                int adminType = (Integer) map.get("adminType");
                obj.put("adminType", adminType);
                if (adminType > -1) {
                    obj.put("isCheck",
                            checkInService.isCheckInToday(user.getUid(),
                            c.getClubId()));
                } else {
                    obj.put("isCheck", false);
                }
                arr.add(obj);
            }
            json.put("data", arr);
            AppUtils.setSuccessCode(json);
        }
        //showType=0时才会返回相关的数组
        if (showType == 0) {
            if (type == 2) { // 全国排名
                // 获取前20名
                List<Club> list = clubService.listClubBySortForList(
                        ClubService.SORT_COUNTRY_TYPE, PAGE_NUM, PAGE_SIZE, 0L,
                        0L, 0, 0);
                for (Club club : list) {
                    JSONObject obj = clubService.setTopClub2Json(club,
                            sourceAgent);
                    Map<String, Object> map = clubService
                            .getAdminTypeAndIdByMember(clubMember,
                            memberApplications, club);
                    int adminType = (Integer) map.get("adminType");
                    obj.put("adminType", adminType);
                    if (adminType > -1) {
                        obj.put("isCheck", checkInService.isCheckInToday(
                                user.getUid(), club.getClubId()));
                    } else {
                        obj.put("isCheck", false);
                    }
                    arr.add(obj);
                }
                // 获取本车友会排名的前后2名
                if (rank > 0L) {
                    int beginRank = rank - 2 <= 0 ? 1 : rank - 2;
                    int endRank = rank + 2;
                    List<Club> list5Clubs = clubService.listClubBySortForList(
                            ClubService.SORT_COUNTRY_TYPE, PAGE_NUM, PAGE_SIZE,
                            0L, 0L, beginRank, endRank);
                    for (Club club : list5Clubs) {
                        JSONObject obj = clubService.setTopClub2Json(club,
                                sourceAgent);
                        Map<String, Object> map = clubService
                                .getAdminTypeAndIdByMember(clubMember,
                                memberApplications, club);
                        int adminType = (Integer) map.get("adminType");
                        obj.put("adminType", adminType);
                        if (adminType > -1) {
                            obj.put("isCheck", checkInService.isCheckInToday(
                                    user.getUid(), club.getClubId()));
                        } else {
                            obj.put("isCheck", false);
                        }
                        arrIndex.add(obj);
                    }
                }
                AppUtils.setSuccessCode(json);
            }

            if (type == 3 && user != null && brandIdByClub > 0) { // 车系排名
                // 获取前20名
                List<Club> list = clubService.listClubBySortForList(
                        ClubService.SORT_SERIES_TYPE, PAGE_NUM, PAGE_SIZE,
                        brandIdByClub, 0L, 0, 0);
                for (Club club : list) {
                    JSONObject obj = clubService.setTopClub2Json(club,
                            sourceAgent);
                    Map<String, Object> map = clubService
                            .getAdminTypeAndIdByMember(clubMember,
                            memberApplications, club);
                    int adminType = (Integer) map.get("adminType");
                    obj.put("adminType", adminType);
                    if (adminType > -1) {
                        obj.put("isCheck", checkInService.isCheckInToday(
                                user.getUid(), club.getClubId()));
                    } else {
                        obj.put("isCheck", false);
                    }
                    arr.add(obj);
                }
                // 获取本车友会排名的前后2名
                if (brandRank > 0L) {
                    int beginRank = brandRank - 2 <= 0 ? 1 : brandRank - 2;
                    int endRank = brandRank + 2;
                    List<Club> list5Clubs = clubService.listClubBySortForList(
                            ClubService.SORT_SERIES_TYPE, PAGE_NUM, PAGE_SIZE,
                            brandIdByClub, 0L, beginRank, endRank);
                    for (Club club : list5Clubs) {
                        JSONObject obj = clubService.setTopClub2Json(club,
                                sourceAgent);
                        Map<String, Object> map = clubService
                                .getAdminTypeAndIdByMember(clubMember,
                                memberApplications, club);
                        int adminType = (Integer) map.get("adminType");
                        obj.put("adminType", adminType);
                        if (adminType > -1) {
                            obj.put("isCheck", checkInService.isCheckInToday(
                                    user.getUid(), club.getClubId()));
                        } else {
                            obj.put("isCheck", false);
                        }
                        arrIndex.add(obj);
                    }
                }
                AppUtils.setSuccessCode(json);
            }

            if (type == 4 && user != null && provinceIdByClub > 0) { // 地区排名
                List<Club> list = clubService.listClubBySortForList(
                        ClubService.SORT_REGION_TYPE, PAGE_NUM, PAGE_SIZE, 0L,
                        provinceIdByClub, 0, 0);
                for (Club club : list) {
                    JSONObject obj = clubService.setTopClub2Json(club,
                            sourceAgent);
                    Map<String, Object> map = clubService
                            .getAdminTypeAndIdByMember(clubMember,
                            memberApplications, club);
                    int adminType = (Integer) map.get("adminType");
                    obj.put("adminType", adminType);
                    if (adminType > -1) {
                        obj.put("isCheck", checkInService.isCheckInToday(
                                user.getUid(), club.getClubId()));
                    } else {
                        obj.put("isCheck", false);
                    }
                    arr.add(obj);
                }
                // 获取本车友会排名的前后2名
                if (provinceRank > 0L) {
                    int beginRank = provinceRank - 2 <= 0 ? 1 : provinceRank - 2;
                    int endRank = provinceRank + 2;
                    List<Club> list5Clubs = clubService.listClubBySortForList(
                            ClubService.SORT_REGION_TYPE, PAGE_NUM, PAGE_SIZE,
                            0L, provinceIdByClub, beginRank, endRank);
                    for (Club club : list5Clubs) {
                        JSONObject obj = clubService.setTopClub2Json(club,
                                sourceAgent);
                        Map<String, Object> map = clubService
                                .getAdminTypeAndIdByMember(clubMember,
                                memberApplications, club);
                        int adminType = (Integer) map.get("adminType");
                        obj.put("adminType", adminType);
                        if (adminType > -1) {
                            obj.put("isCheck", checkInService.isCheckInToday(
                                    user.getUid(), club.getClubId()));
                        } else {
                            obj.put("isCheck", false);
                        }
                        arrIndex.add(obj);
                    }
                }
                AppUtils.setSuccessCode(json);
            }
            json.put("data", arr);
            json.put("clubIndexData", arrIndex);
        }

        if (type > 4 || type < 0) {
            AppUtils.setDataErrorCode(json, "非法参数type!");
        }

        print(resp, json.toJSONString(), callback);
    }

    /**
     * 查询已加入车友会列表，目前给个人中心调用(APP)，大首页通栏调用 目前还提供给平台那边调用
     *
     * @param req
     * @param resp
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/club/getJoinedClubList.do", method = RequestMethod.GET)
    public void getJoinedClubList(HttpServletRequest req, HttpServletResponse resp) {
        WebUtils.setEncoding(req, resp);
        JSONObject json = new JSONObject();
        long uid = WebUtils.paramInt(req, "uid", 0);
        int sourceAgent = WebUtils.paramInt(req, "source_agent", DEF_SOURCE_AGENT);
        String callback = WebUtils.param(req, "callback", "");
        User user = userService.findUser(uid);
        if (user != null && uid > 0) {
            JSONArray arr = new JSONArray();
            List<ClubMember> list = memberService.listClubMemberByUser(uid);
            if (list != null && !list.isEmpty()) {
                for (ClubMember cm : list) {
                    Club club = clubService.getClub(cm.getClubId());
                    ClubAddress a = clubService.getAddress(cm.getClubId());
                    JSONObject jsonObject = parseJSONObject(club, a, user, sourceAgent);
                    jsonObject.put("adminType", cm.getAdminType());
                    jsonObject.put("memberId", cm.getId());
                    arr.add(jsonObject);
                }
            }
            json.put("data", arr);
            AppUtils.setSuccessCode(json);
        } else {
            AppUtils.setNoLoginCode(json);

        }
        try {
            PrintWriter write = resp.getWriter();
            if (StringUtils.isNotBlank(callback)) {
                write.println(EncodeUtils.encodeForHTML(callback, DEF_SOURCE_AGENT) + "(" + json.toJSONString() + ")");
            } else {
                write.println(json.toJSONString());
            }
            write.flush();
            write.close();
        } catch (IOException ex) {
            log.error("error", ex);
        }
    }

    /**
     * 个人中心调用车友会接口 根据用户获取加入车友会接口
     *
     * @param req
     * @param resp
     */
    @ResponseBody
    @RequestMapping(value = "/club/getJoinedClubListByUser.do", method = RequestMethod.GET)
    public void getJoinedClubListByUser(HttpServletRequest req, HttpServletResponse resp) {
        String req_enc = WebUtils.param(req, "req_enc", "GBK");
        String resp_enc = WebUtils.param(req, "resp_enc", "GBK"); //个人中心编码是GBK,为了迁就个人中心默认用GBK
        try {
            req.setCharacterEncoding(req_enc);
            resp.setCharacterEncoding(resp_enc);

        } catch (UnsupportedEncodingException ex) {
            log.error("error", ex);
        }
        JSONObject json = new JSONObject();
        long uid = WebUtils.paramInt(req, "uid", 0);
        String callback = WebUtils.param(req, "callback", "");
        int sourceAgent = WebUtils.paramInt(req, "source_agent", DEF_SOURCE_AGENT);
        User user;
        if (uid == 0) {
            user = userAuth.getUser(req, resp);
            uid = user.getUid();
        } else {
            user = userService.findUser(uid);
        }
        if (uid > 0) {
            JSONArray arr = new JSONArray();
            List<ClubMember> list = memberService.listClubMemberByUser(uid);
            if (list != null && !list.isEmpty()) {
                for (ClubMember cm : list) {
                    Club club = clubService.getClub(cm.getClubId());
                    ClubAddress a = clubService.getAddress(cm.getClubId());
                    JSONObject jsonObject = parseJSONObject(club, a, user, sourceAgent);
                    jsonObject.put("memberId", cm.getId());
                    jsonObject.put("status", 1);
                    arr.add(jsonObject);
                }
            } else {//现在一个用户只能加入一个车友会如果有数据，没必要再查了
                List<MemberApplication> memberApplications = memberService.listMemberApplicationsByUserId(uid);
                for (MemberApplication m : memberApplications) {
                    Club club = clubService.getClub(m.getClubId());
                    ClubAddress a = clubService.getAddress(m.getClubId());
                    JSONObject jsonObject = parseJSONObject(club, a, user, sourceAgent);
                    jsonObject.put("memberId", m.getId());
                    jsonObject.put("status", 0);
                    arr.add(jsonObject);
                }
            }
            json.put("data", arr);
            json.put("code", 0);
        } else {
            json.put("code", -1);
            json.put("message", "用户没有登录或者没有传参");
        }
        try {
            PrintWriter write = resp.getWriter();
            if (StringUtils.isNotBlank(callback)) {
                write.println(EncodeUtils.encodeForHTML(callback, DEF_SOURCE_AGENT) + "(" + json.toJSONString().replaceAll("<", "&lt;").replaceAll(">", "&gt;") + ")");
            } else {
                write.println(json.toJSONString().replaceAll("<", "&lt;").replaceAll(">", "&gt;"));
            }
            write.flush();
            write.close();
        } catch (IOException ex) {
            log.error("error", ex);
        }
    }

    /**
     * 查询已加入车友会列表，目前给前端cms调用
     *
     * @param req
     * @param resp
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/club/listMyJoinClub.do", method = RequestMethod.GET)
    public void listMyJoinClub(HttpServletRequest req, HttpServletResponse resp) {
//        WebUtils.setEncoding(req, resp);
        try {
            req.setCharacterEncoding("GBK");
            resp.setCharacterEncoding("GBK");
            resp.setContentType("text/html; charset=GBK");

        } catch (UnsupportedEncodingException ex) {
            log.error("error", ex);
        }
        JSONObject json = new JSONObject();
        long uid = WebUtils.paramInt(req, "uid", 0);
        int sourceAgent = WebUtils.paramInt(req, "source_agent", DEF_SOURCE_AGENT);
        String callback = WebUtils.param(req, "callback", "");
        if (uid > 0) {
            json.put("data", clubService.getUserClubById(uid, sourceAgent));
        } else {
            json.put("message", "用户没有登录或者没有传参");
        }
        try {
            PrintWriter write = resp.getWriter();
            if (StringUtils.isNotBlank(callback)) {
                write.println(EncodeUtils.encodeForHTML(callback, DEF_SOURCE_AGENT) + "(" + json.toJSONString() + ")");
            } else {
                write.println(json.toJSONString());
            }
            write.flush();
            write.close();
        } catch (IOException ex) {
            log.error("error", ex);
        }
    }

    /**
     * 批量查询用户加入的车友会
     *
     * @param req
     * @param resp
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/club/listMyJoinClubs.do", method = RequestMethod.GET)
    public void listMyJoinClubs(HttpServletRequest req, HttpServletResponse resp) {
//        WebUtils.setEncoding(req, resp);
        try {
            req.setCharacterEncoding("GBK");
            resp.setCharacterEncoding("GBK");
            resp.setContentType("text/html; charset=GBK");

        } catch (UnsupportedEncodingException ex) {
            log.error("error", ex);
        }
        String uids = WebUtils.paramTrim(req, "uids", ""); // 多个以逗号分隔
        int sourceAgent = WebUtils.paramInt(req, "source_agent", DEF_SOURCE_AGENT);
        String callback = WebUtils.param(req, "callback", "");
        JSONArray arr = new JSONArray();
        if (StringUtils.isNotBlank(uids)) {

            String[] ids = uids.split(",");
            for (String id : ids) {
                if (StringUtils.isNotBlank(id)) {
                    JSONObject obj = new JSONObject();
                    obj.put("userId", id);
                    obj.put("data", clubService.getUserClubById(Integer.parseInt(id.toString()), sourceAgent));
                    arr.add(obj);
                }
            }
        }
        try {
            PrintWriter write = resp.getWriter();
            if (StringUtils.isNotBlank(callback)) {
                write.println(EncodeUtils.encodeForHTML(callback, DEF_SOURCE_AGENT) + "(" + arr.toString() + ")");
            } else {
                write.println(arr.toString());
            }
            write.flush();
            write.close();
        } catch (IOException ex) {
            log.error("error", ex);
        }
    }

    /**
     * 车友会名称检测(app共用，code用PC端，ps:抽离时去掉这段)
     *
     * @param req
     * @param resp
     */
    @ResponseBody
    @RequestMapping(value = "/club/checkClubName.do", method = RequestMethod.GET)
    public JSONObject checkClubName(HttpServletRequest req, HttpServletResponse resp) {
        String name = WebUtils.paramTrim(req, "name", "");
        String result = clubService.checkClubName(name);
        JSONObject json = new JSONObject();
        int code = -1;
        String message;
        if (result.equals("true")) {
            code = 1;
            message = "验证通过";
        } else {
            message = result;
        }
        json.put("code", code);
        json.put("message", message);
        return json;
    }

    /**
     * 车友会QQ群号
     *
     * @param req
     * @param resp
     */
    @ResponseBody
    @RequestMapping(value = "/club/checkClubQQGroup.do", method = RequestMethod.GET)
    public JSONObject checkClubQQGroup(HttpServletRequest req, HttpServletResponse resp) {
        String qq = WebUtils.paramTrim(req, "qqGroup", "");
        String result = clubService.checkClubQQGroup(qq);
        JSONObject json = new JSONObject();
        int code = -1;
        String message;
        if (result.equals("true")) {
            code = 1;
            message = "验证通过";
        } else {
            message = result;
        }
        json.put("code", code);
        json.put("message", message);
        return json;
    }

    /**
     * 车友会个性域名检测(APP共用，code暂用PC端 ps:抽出来时请去掉这个）
     *
     * @param req
     * @param resp
     */
    @ResponseBody
    @RequestMapping(value = "/club/checkClubUrl.do", method = RequestMethod.GET)
    public JSONObject checkClubUrl(HttpServletRequest req, HttpServletResponse resp) {
        String clubUrl = WebUtils.paramTrim(req, "clubUrl", "").replaceAll(" ", "").toLowerCase();
        JSONObject json = new JSONObject();
        String result = clubService.checkClubUrl(clubUrl);
        int code = -1;
        String message;
        if (result.equals("true")) {
            code = 1;
            message = "验证通过";
        } else {
            message = result;
        }
        json.put("code", code);
        json.put("message", message);
        return json;
    }

    /**
     * 手机验证
     *
     * @param req
     * @param resp
     */
    @ResponseBody
    @RequestMapping(value = "/club/checkClubPhone.do", method = RequestMethod.GET)
    public JSONObject checkClubPhone(HttpServletRequest req, HttpServletResponse resp) {
        String phone = WebUtils.paramTrim(req, "phone", "").replaceAll(" ", "").toLowerCase();
        JSONObject json = new JSONObject();
        String result = clubService.checkClubPhone(phone);
        int code = -1;
        String message;
        if (result.equals("true")) {
            code = 1;
            message = "验证通过";
        } else {
            message = result;
        }
        json.put("code", code);
        json.put("message", message);
        return json;
    }

    /**
     * 根据用户ID或者地区ID获取车友会列表
     *
     * @throws UnsupportedEncodingException
     */
    @ResponseBody
    @RequestMapping(value = "/club/getClubByRegionId.do", method = RequestMethod.GET)
    public void getClubByRegionId(HttpServletRequest req, HttpServletResponse resp) {
        resp.setCharacterEncoding("GBK");
        resp.setContentType("text/html; charset=GBK");
        String originHeader = req.getHeader("Origin");
        if (StringUtils.isNotBlank(originHeader)) {
            resp.setHeader("Access-Control-Allow-Credentials", "true");
            resp.setHeader("Access-Control-Allow-Origin", originHeader);
        }
        long regionId = WebUtils.paramLong(req, "regionId", 0);
        String callback = WebUtils.param(req, "callback", "");
        int numLimit = WebUtils.paramInt(req, "numLimit", 0);
        int sourceAgent = WebUtils.paramInt(req, "source_agent", DEF_SOURCE_AGENT);
        List<Club> listClub = clubService.waplistClubByRegion(regionId, numLimit);
        JSONArray jsonArray = new JSONArray();
        if (listClub != null && !listClub.isEmpty()) {
            for (Club club : listClub) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("clubId", club.getClubId());
                jsonObject.put("clubName", EncodeUtils.encodeForHTML(club.getName(), sourceAgent));
                jsonObject.put("logo", EncodeUtils.encodeForHTML(club.getLogo(), sourceAgent));
                jsonObject.put("totalPetrol", petrolService.getValidPetrol(club.getClubId()).getTotalPetrol());
                jsonObject.put("regionRank", club.getRegionRank());
                jsonObject.put("brandRank", club.getBrandRank());
                jsonObject.put("provinceRank", club.getProvinceRank());
                jsonObject.put("rank", club.getRank());
                jsonObject.put("qqGroup", club.getQqGroup());
                jsonObject.put("seriesName", EncodeUtils.encodeForHTML(club.getSeriesName(), sourceAgent));
                jsonObject.put("provinceName", EncodeUtils.encodeForHTML(club.getProvinceName(), sourceAgent));
                jsonObject.put("cityName", EncodeUtils.encodeForHTML(club.getCityName(), sourceAgent));
                jsonObject.put("introduce", EncodeUtils.encodeForHTML(club.getIntroduce(), sourceAgent));
                jsonObject.put("url", systemConfig.getRoot() + "/" + club.getClubUrl() + "/");
                jsonObject.put("memberSum", club.getMemberNum());
                jsonObject.put("regionId", regionId);
                jsonObject.put("memberSum", club.getMemberNum());
                jsonObject.put("levelId", club.getLevelId());
                jsonArray.add(jsonObject);
            }
        }
        String result;
        if (StringUtils.isNotBlank(callback)) {
            result = EncodeUtils.encodeForHTML(callback, DEF_SOURCE_AGENT) + "(" + jsonArray.toJSONString() + ")";
        } else {
            result = jsonArray.toJSONString();
        }
        //缺缓存
        try {
            PrintWriter out = resp.getWriter();
            out.print(result);
            out.flush();
            out.close();
        } catch (IOException e) {
            log.error("/club/getClubByRegionId.do接口出错", e);
        }
    }

    /**
     * 车友会信息转换JSON数据
     *
     * @param club
     * @param a
     * @param user
     * @param sourceAgent
     * @return
     */
    private JSONObject parseJSONObject(Club club, ClubAddress a, User user, int sourceAgent) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("clubId", club.getClubId());
        jsonObject.put("clubUrl", club.getClubUrl());
        jsonObject.put("clubStatus", club.getStatus());
        jsonObject.put("name", EncodeUtils.encodeForHTML(club.getName(), sourceAgent));
        jsonObject.put("logo", EncodeUtils.encodeForHTML(club.getLogo(), sourceAgent));
        jsonObject.put("memberNum", club.getMemberNum());
        jsonObject.put("totalPetrol", petrolService.getValidPetrol(club.getClubId()).getTotalPetrol());
        jsonObject.put("level", club.getLevelId());
        jsonObject.put("levelName", EncodeUtils.encodeForHTML(clubLevelService.getById(club.getLevelId()).getLevelName(), sourceAgent));
        jsonObject.put("brandId", club.getBrandId());
        jsonObject.put("brandName", club.getBrandName());
        String activityName = "";
        List<Activity> listActivity = activityService.getNewActivity(club.getClubId(), 1);
        if (listActivity != null && !listActivity.isEmpty()) {
            Activity activity = listActivity.get(0);
            activityName = activity.getTitle();

        }
        jsonObject.put("activityName", EncodeUtils.encodeForHTML(activityName, sourceAgent));
        jsonObject.put("commentSum", commentService.countByClubId(club.getClubId()));
        jsonObject.put("regionRank", club.getRegionRank());
        jsonObject.put("brandRank", club.getBrandRank());
        jsonObject.put("provinceRank", club.getProvinceRank());
        jsonObject.put("rank", club.getRank());
        jsonObject.put("qqGroup", club.getQqGroup());
        jsonObject.put("albumSum", albumService.countAlbumByClubId(club.getClubId()));
        jsonObject.put("photoSum", albumService.countPhotoByClubId(club.getClubId()));
        jsonObject.put("topicSum", topicService.countByClubId(club.getClubId()));
        jsonObject.put("vipNum", club.getVipNum());
        jsonObject.put("totalPetrol", club.getTotalPetrol());
        jsonObject.put("activitySum", activityService.countActivityByClubId(club.getClubId()));
        jsonObject.put("seriesName", EncodeUtils.encodeForHTML(club.getSeriesName(), sourceAgent));
        jsonObject.put("seriesId", club.getSeriesId());
        jsonObject.put("provinceId", club.getProvinceId());
        jsonObject.put("provinceName", EncodeUtils.encodeForHTML(club.getProvinceName(), sourceAgent));
        jsonObject.put("cityId", club.getCityId());
        jsonObject.put("cityName", EncodeUtils.encodeForHTML(club.getCityName(), sourceAgent));
        jsonObject.put("introduce", EncodeUtils.encodeForHTML(club.getIntroduce(), sourceAgent));
        jsonObject.put("announcement", EncodeUtils.encodeForHTML(clubService.getNotice(club.getClubId()).getContent(), sourceAgent));
        jsonObject.put("addressProvinceId", a.getProvinceId());
        jsonObject.put("addressCityId", club.getCityId());
        jsonObject.put("addressUserName", EncodeUtils.encodeForHTML(a.getName(), sourceAgent));
        jsonObject.put("addressPhone", a.getPhone());
        jsonObject.put("addressProvinceName", EncodeUtils.encodeForHTML(a.getProvinceName(), sourceAgent));
        jsonObject.put("addressCityName", EncodeUtils.encodeForHTML(a.getCityName(), sourceAgent));
        jsonObject.put("addressDetail", EncodeUtils.encodeForHTML(a.getAddress(), sourceAgent));
        jsonObject.put("addressPostcode", a.getPostcode());
        //              jsonObject.put("adminType", cm.getAdminType());

        jsonObject.put("userName", EncodeUtils.encodeForHTML(user.getUsername(), sourceAgent));
        jsonObject.put("userNikeName", EncodeUtils.encodeForHTML(user.getNickname(), sourceAgent));
        jsonObject.put("userPhone", user.getPhone());
        jsonObject.put("userCar", EncodeUtils.encodeForHTML(user.getCarInfo(), sourceAgent));
        jsonObject.put("userProvince", EncodeUtils.encodeForHTML(user.getProvince(), sourceAgent));
        jsonObject.put("userCity", EncodeUtils.encodeForHTML(user.getCity(), sourceAgent));
        jsonObject.put("userGener", user.getGender());
        //    jsonObject.put("status", 1);
        return jsonObject;
    }

    /**
     * 前段快捷查询调用
     *
     * @param req
     * @param resp
     */
    @ResponseBody
    @RequestMapping(value = "/club/getClubByChoose.do", method = RequestMethod.GET)
    public JSONObject getClubByChoose(HttpServletRequest req, HttpServletResponse resp) {
        int sourceAgent = WebUtils.paramInt(req, "source_agent", DEF_SOURCE_AGENT);
        List<Club> listClub = clubService.waplistClubByRegion(0, 0);
        JSONObject json = new JSONObject();
        if (listClub != null && !listClub.isEmpty()) {
            JSONArray array = new JSONArray();
            for (Club club : listClub) {
                JSONObject obj = new JSONObject();
                obj.put("clubId", club.getClubId());
                obj.put("name", EncodeUtils.encodeForHTML(club.getName(), sourceAgent));
                obj.put("logo", club.getLogo());
                obj.put("provinceId", club.getProvinceId());
                obj.put("provinceName", EncodeUtils.encodeForHTML(club.getProvinceName(), sourceAgent));
                obj.put("cityId", club.getCityId());
                obj.put("cityName", EncodeUtils.encodeForHTML(club.getCityName(), sourceAgent));
                obj.put("brandId", club.getBrandId());
                obj.put("brandName", EncodeUtils.encodeForHTML(club.getBrandName(), sourceAgent));
                obj.put("seriesId", club.getSeriesId());
                obj.put("qqGroup", club.getQqGroup());
                obj.put("seriesName", EncodeUtils.encodeForHTML(club.getSeriesName(), sourceAgent));
                obj.put("petrol", club.getTotalPetrol());
                obj.put("introduce", EncodeUtils.encodeForHTML(club.getIntroduce(), sourceAgent).replaceAll("\n|\r|\f", ""));
                obj.put("levelId", club.getLevelId());
                obj.put("memberNum", club.getMemberNum());
                obj.put("vipNum", club.getVipNum());
                obj.put("url", systemConfig.getRoot() + "/" + club.getClubUrl() + "/");
                array.add(obj);
            }
            json.put("date", array);
        } else {
            json.put("msg", "无车友会数据");
        }
        return json;
    }

    /**
     * 根据地区分类车友会 供cms调用
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/club/listClubByPlaceOrBrand.do")
    @ResponseBody
    public void listClubByPlaceOrBrand(HttpServletRequest req, HttpServletResponse resp) {
        WebUtils.setEncoding(req, resp);
        WebUtils.setCacheHeader(resp, 3600);
        String callback = WebUtils.param(req, "callback", "");
        int type = WebUtils.paramInt(req, "type", 1);  //类别，默认1,》品牌  DEF_SOURCE_AGENT》区域
        int sourceAgent = WebUtils.paramInt(req, "source_agent", DEF_SOURCE_AGENT);
        int limit = WebUtils.paramInt(req, "limit", 10, 1, 100);
        JSONArray arr;
        if (type == 1) {
            arr = clubService.getClubListGroupByBrand(sourceAgent, limit);
        } else {
            arr = clubService.getClubListGroupByArea(sourceAgent, limit);
        }
        print(resp, arr.toJSONString(), callback);
    }

    /**
     * 获取用户在指定车友会权限
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/club/getOperateAuthority")
    @ResponseBody
    public JSONObject getOperateAuthority(HttpServletRequest request, HttpServletResponse response) {
        long clubId = WebUtils.paramLong(request, "clubId", 0);
        long userId = WebUtils.paramLong(request, "userId", 0);
        JSONObject json = new JSONObject();
        User user = userService.findUser(userId);
        if (userId > 0) {
            if (user == null) {
                user = userAuth.authUser(userId);
            }
            if (user != null && user.getUid() > 0) {
                if (clubId > 0) {
                    int type = clubService.getClubRelationByUser(user, clubId);
                    json.put("clubId", clubId);
                    json.put("adminType", type);
                    if (type != -1) {
                        json.put("message", "用户已经加入车友会或已经申请加入车友会");
                    }
                } else {
                    int type = clubService.getClubRelationByUser(user, 0);
                    json.put("adminType", clubService.getClubRelationByUser(user, 0));
                    if (type == -2) {
                        json.put("message", "用户已经加入其他车友会或已经申请加入其他车友会");
                    }
                }
            } else {
                AppUtils.setDataErrorCode(json, "太平洋账号不存在");
            }
        } else {
            AppUtils.setDataErrorCode(json, "用户ID不能为空");
        }
        return json;
    }

    @RequestMapping(value = "/club/isAdmin", method = RequestMethod.GET)
    @ResponseBody
    public String isClubAdmin(HttpServletRequest request, HttpServletResponse response) {
        long clubId = WebUtils.paramLong(request, "clubId", 0);
        long userId = WebUtils.paramLong(request, "userId", 0);
        JSONObject json = new JSONObject();
        json.put("code", 0);
        if (clubId > 0) {
            if (userId == 0) {
                User user = userAuth.getUser(request, response);
                if (user != null && memberService.isClubNormalAdmin(user.getUid(), clubId)) {
                    json.put("code", 1);
                }
            }
        }
        return json.toJSONString();
    }

    public JSONObject parseRecommendClubJSON(Club club, User user, int sourceAgent) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("clubId", club.getClubId());
        jsonObject.put("clubStatus", club.getStatus());
        jsonObject.put("name", EncodeUtils.encodeForHTML(club.getName(), sourceAgent));
        jsonObject.put("logo", EncodeUtils.encodeForHTML(club.getLogo(), sourceAgent));
        jsonObject.put("memberSum", club.getMemberNum());
        jsonObject.put("totalPetrol", petrolService.getValidPetrol(club.getClubId()).getTotalPetrol());
        jsonObject.put("level", club.getLevelId());
        jsonObject.put("levelName", EncodeUtils.encodeForHTML(clubLevelService.getById(club.getLevelId()).getLevelName(), sourceAgent));
        jsonObject.put("brandName", club.getBrandName());
        jsonObject.put("rank", club.getRank());
        jsonObject.put("regionRank", club.getRegionRank());
        jsonObject.put("provinceRank", club.getProvinceRank());
        jsonObject.put("brandRank", club.getBrandRank());
        jsonObject.put("rank", club.getRank());
        jsonObject.put("seriesName", EncodeUtils.encodeForHTML(club.getSeriesName(), sourceAgent));
        jsonObject.put("clubUrl", club.getClubUrl());
        return jsonObject;
    }

    public JSONObject parseClubJSON(Club club, User user, int sourceAgent) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("clubId", club.getClubId());
        jsonObject.put("clubStatus", club.getStatus());
        jsonObject.put("name", EncodeUtils.encodeForHTML(club.getName(), sourceAgent));
        jsonObject.put("logo", EncodeUtils.encodeForHTML(club.getLogo(), sourceAgent));
        jsonObject.put("memberSum", club.getMemberNum());
        jsonObject.put("totalPetrol", petrolService.getValidPetrol(club.getClubId()).getTotalPetrol());
        jsonObject.put("level", club.getLevelId());
        jsonObject.put("levelName", EncodeUtils.encodeForHTML(clubLevelService.getById(club.getLevelId()).getLevelName(), sourceAgent));
        String activityName = "";
        List<Activity> listActivity = activityService.getNewActivity(club.getClubId(), 1);
        if (listActivity != null && !listActivity.isEmpty()) {
            Activity activity = listActivity.get(0);
            if (activity != null) {
                activityName = activity.getTitle();
            }
        }
        jsonObject.put("brandName", club.getBrandName());
        jsonObject.put("rank", club.getRank());
        jsonObject.put("qqGroup", club.getQqGroup());
        jsonObject.put("activityName", EncodeUtils.encodeForHTML(activityName, sourceAgent));
        jsonObject.put("commentSum", commentService.countByClubId(club.getClubId()));
        jsonObject.put("regionRank", club.getRegionRank());
        jsonObject.put("provinceRank", club.getProvinceRank());
        jsonObject.put("brandRank", club.getBrandRank());
        jsonObject.put("rank", club.getRank());
        jsonObject.put("albumSum", albumService.countAlbumByClubId(club.getClubId()));
        jsonObject.put("photoSum", albumService.countPhotoByClubId(club.getClubId()));
        jsonObject.put("topicSum", topicService.countByClubId(club.getClubId()));
        jsonObject.put("activitySum", activityService.countActivityByClubId(club.getClubId()));
        jsonObject.put("seriesName", EncodeUtils.encodeForHTML(club.getSeriesName(), sourceAgent));
        jsonObject.put("provinceName", EncodeUtils.encodeForHTML(club.getProvinceName(), sourceAgent));
        jsonObject.put("cityName", EncodeUtils.encodeForHTML(club.getCityName(), sourceAgent));
        jsonObject.put("introduce", EncodeUtils.encodeForHTML(club.getIntroduce(), sourceAgent));
        jsonObject.put("announcement", EncodeUtils.encodeForHTML(clubService.getNotice(club.getClubId()).getContent(), sourceAgent));
        jsonObject.put("clubUrl", club.getClubUrl());
        return jsonObject;
    }

    private void print(HttpServletResponse resp, String str, String callback) {
        try {
            java.io.PrintWriter w = resp.getWriter();
            if (StringUtils.isNotBlank(callback)) {
                w.println(EncodeUtils.encodeForHTML(callback, DEF_SOURCE_AGENT) + "(" + str + ")");
            } else {
                w.println(str);
            }
            w.flush();
            w.close();
        } catch (IOException ex) {
            log.error("error", ex);
        }
    }

    private void printErrorMsg(HttpServletResponse resp, String msg, String callback) {
        JSONObject json = new JSONObject();
        json.put("code", -1);
        json.put("message", msg);
        print(resp, json.toJSONString(), callback);
    }

    /**
     * 寻找中国车友会星级排名接口 给平台那边用的 对接人 黄平
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/club/getListByUpdateAt", method = RequestMethod.GET)
    @ResponseBody
    public void getListByUpdateAt(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        WebUtils.setCacheHeader(response, 1800);//缓存半个小时
        String dateStr = WebUtils.paramTrim(request, "updateAt", "");
        JSONObject json = new JSONObject();
        Date updateAt = null;
        try {
            updateAt = WebUtils.parseDate(dateStr);
        } catch (IllegalArgumentException e) {
        }
        if (updateAt == null) {
            printErrorMsg(response, "非法日期参数", "");
            return;
        }
        Date now = DateUtils.getNow();
        long sevenDays = 7 * 24 * 3600L * 1000L;
        if ((now.getTime() - updateAt.getTime()) > sevenDays) {
            printErrorMsg(response, "日期太靠前", "");
            return;
        }
        List<Club> list = clubService.getListByUpdateAt(updateAt);
        JSONArray arr = new JSONArray(list.size());
        for (Club c : list) {
            JSONObject obj = new JSONObject();
            obj.put("club_id", c.getClubId());
            obj.put("name", c.getName());
            obj.put("introduce", c.getIntroduce());
            obj.put("level", c.getLevelId());
            obj.put("logo", c.getLogo());
            obj.put("province_name", c.getProvinceName());
            obj.put("city_name", c.getCityName());
            obj.put("region_id", c.getRegionId());
            obj.put("region_name", c.getRegionName());
            obj.put("member_num", c.getMemberNum());
            obj.put("brand_name", c.getBrandName());
            obj.put("series_name", c.getSeriesName());
            obj.put("club_url", c.getClubUrl());
            obj.put("status", c.getStatus());
            arr.add(obj);
        }
        json.put("code", 0);
        json.put("message", "");
        json.put("size", list.size());
        json.put("list", arr);
        print(response, json.toJSONString(), "");
    }

    private JSONObject parseClubJSON(Club c, int sourceAgent) {
        JSONObject obj = new JSONObject();
        obj.put("clubId", c.getClubId());
        obj.put("clubStatus", c.getStatus());
        obj.put("name", EncodeUtils.encodeForHTML(c.getName(), sourceAgent));
        obj.put("logo", EncodeUtils.encodeForHTML(c.getLogo(), sourceAgent));
        obj.put("memberSum", c.getMemberNum());
        obj.put("vipSum", c.getVipNum());
        obj.put("totalPetrol", c.getTotalPetrol());
        obj.put("level", c.getLevelId());
        obj.put("qqGroup", c.getQqGroup());
        obj.put("brandName", EncodeUtils.encodeForHTML(c.getBrandName(), sourceAgent));
        obj.put("rank", c.getRank());
        obj.put("regionRank", c.getRegionRank());
        obj.put("provinceRank", c.getProvinceRank());
        obj.put("brandRank", c.getBrandRank());
        obj.put("seriesName", EncodeUtils.encodeForHTML(c.getSeriesName(), sourceAgent));
        obj.put("provinceName", EncodeUtils.encodeForHTML(c.getProvinceName(), sourceAgent));
        obj.put("cityName", EncodeUtils.encodeForHTML(c.getCityName(), sourceAgent));
        obj.put("introduce", EncodeUtils.encodeForHTML(c.getIntroduce(), sourceAgent));
        obj.put("clubUrl", c.getClubUrl());
        return obj;
    }

    /**
     * 汽车网车友会入口优化开发需求 给大首页调用
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/club/getListByClubIds", method = RequestMethod.GET)
    @ResponseBody
    public void getListByClubIds(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setCacheHeader(response, 3600);//缓存1小时
        WebUtils.setEncoding(request, response);
        String callback = WebUtils.param(request, "callback", "");
        int sourceAgent = WebUtils.paramInt(request, "source_agent", DEF_SOURCE_AGENT);
        String clubIdStr = WebUtils.paramTrim(request, "clubIds", "");
        String[] clubIds = clubIdStr.split(",");
        JSONObject json = new JSONObject();
        if (clubIds == null || clubIds.length == 0) {
            printErrorMsg(response, "请输入IDs", callback);
            return;
        }
        int MAX_SIZE = 20;
        if (clubIds.length > MAX_SIZE) {
            printErrorMsg(response, "最多只能输入" + MAX_SIZE + "个ID", callback);
            return;
        }
        List<Long> ids = new ArrayList<Long>(clubIds.length);
        for (String id : clubIds) {
            try {
                long cId = Long.parseLong(id);
                ids.add(cId);
            } catch (NumberFormatException e) {
                printErrorMsg(response, "非法ID", callback);
                return;
            }
        }
        JSONArray arr = new JSONArray(ids.size());
        for (Long id : ids) {
            Club c = clubService.getValidClub(id);
            if (c == null) {
                continue;
            }
            JSONObject obj = parseClubJSON(c, sourceAgent);
            arr.add(obj);
        }
        json.put("code", 0);
        json.put("message", "");
        json.put("size", arr.size());
        json.put("list", arr);
        print(response, json.toJSONString(), callback);
    }

    /**
     * 分站接口 在各地分站首页使用，根据城市ID出车友会,页面 http://www.pcauto.com.cn/qcbj/gz/
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/club/getListByCityId", method = RequestMethod.GET)
    @ResponseBody
    public void getListByCityId(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setCacheHeader(response, 3600);//缓存1小时
        WebUtils.setEncoding(request, response);
        String callback = WebUtils.param(request, "callback", "");
        int sourceAgent = WebUtils.paramInt(request, "source_agent", DEF_SOURCE_AGENT);
        long cityId = WebUtils.paramInt(request, "cityId", 0);
        long provinceId = WebUtils.paramInt(request, "provinceId", 0);
        int level = WebUtils.paramInt(request, "level", 0);
        int MAX_SIZE = 10;//限制最多只出10条数据
        int size = WebUtils.paramInt(request, "size", MAX_SIZE);
        JSONObject json = new JSONObject();
        if (cityId == 0 && provinceId == 0) {
            printErrorMsg(response, "请输入cityId|provinceId", callback);
            return;
        }
        if (size > MAX_SIZE) {
            printErrorMsg(response, "最多只能查询" + MAX_SIZE + "个车友会", callback);
            return;
        }
        Pager<Club> pager = clubService.listClubByCityId(cityId, provinceId, 1, size, level);
        List<Club> list;
        if (pager.getResultList() != null) {
            list = pager.getResultList();
        } else {
            list = Collections.EMPTY_LIST;
        }
        JSONArray arr = new JSONArray(list.size());
        for (Club c : list) {
            JSONObject obj = parseClubJSON(c, sourceAgent);
            arr.add(obj);
        }
        json.put("code", 0);
        json.put("message", "");
        json.put("size", arr.size());
        if (list.size() > 0) {
            Club club = list.get(0);
            String link = "http://club.pcauto.com.cn/all/c-p" + club.getProvinceId() + (cityId > 0 ? "-s" + club.getCityId() : "") + ".html";
            json.put("link", link);
        }
        json.put("list", arr);
        print(response, json.toJSONString(), callback);
    }

    /**
     * 汽车网车友会入口优化开发需求 给 车系频道首页-论坛区 调用
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/club/getListBySid", method = RequestMethod.GET)
    @ResponseBody
    public void getListBySid(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setCacheHeader(response, 3600);//缓存1小时
        WebUtils.setEncoding(request, response);
        String callback = WebUtils.param(request, "callback", "");
        int sourceAgent = WebUtils.paramInt(request, "source_agent", DEF_SOURCE_AGENT);
        long sid = WebUtils.paramInt(request, "sid", 0);
        JSONObject json = new JSONObject();
        if (sid == 0) {
            printErrorMsg(response, "请输入车系ID", callback);
            return;
        }
        List<Club> list = clubService.getListBySid(sid);
        JSONArray arr = new JSONArray(list.size());
        for (Club c : list) {
            JSONObject obj = parseClubJSON(c, sourceAgent);
            arr.add(obj);
        }
        json.put("code", 0);
        json.put("message", "");
        json.put("size", arr.size());
        json.put("list", arr);
        print(response, json.toJSONString(), callback);
    }

    /**
     * 根据品牌获取车友会列表 给大首页调用
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/club/getListByBrandId", method = RequestMethod.GET)
    @ResponseBody
    public void getListByBrandId(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setCacheHeader(response, 3600);//缓存1小时
        WebUtils.setEncoding(request, response);
        String callback = WebUtils.param(request, "callback", "");
        int sourceAgent = WebUtils.paramInt(request, "source_agent", DEF_SOURCE_AGENT);
        int pageNo = WebUtils.paramInt(request, "pageNo", 1);
        int pageSize = WebUtils.paramInt(request, "pageSize", 10, MIN_PAGESIZE, MAX_PAGESIZE);
        long brandId = WebUtils.paramInt(request, "brandId", 0);
        JSONObject json = new JSONObject();
        if (brandId == 0) {
            printErrorMsg(response, "请输入品牌ID", callback);
            return;
        }
        List<Club> list = clubService.getListByBrandId(brandId, pageNo, pageSize);
        JSONArray arr = new JSONArray(list.size());
        for (Club c : list) {
            JSONObject obj = parseClubJSON(c, sourceAgent);
            arr.add(obj);
        }
        json.put("code", 0);
        json.put("message", "");
        json.put("size", arr.size());
        json.put("list", arr);
        print(response, json.toJSONString(), callback);
    }

    /**
     * 车友会搜索页面列表
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/club/search.do", method = RequestMethod.GET)
    public String search(HttpServletRequest req, HttpServletResponse resp) {
        long provinceId = WebUtils.paramInt(req, "provinceId", 0);
        long brandId = WebUtils.paramInt(req, "brandId", 0);
        long seriesId = WebUtils.paramInt(req, "seriesId", 0);
        long cityId = WebUtils.paramInt(req, "cityId", 0);
        int themeId = WebUtils.paramInt(req, "themeId", 0);
        int pageNo = WebUtils.paramInt(req, "pageNo", 1);
        int pageSize = WebUtils.paramInt(req, "pageSize", 10, MIN_PAGESIZE, MAX_PAGESIZE);
        if ((req.getParameter("provinceId") != null && provinceId <= 0)
                || (req.getParameter("brandId") != null && brandId <= 0)
                || (req.getParameter("seriesId") != null && seriesId <= 0)
                || (req.getParameter("cityId") != null && cityId <= 0)
                || (req.getParameter("themeId") != null && themeId <= 0)
                || pageNo <= 0) {
            try {
                resp.sendError(404);
                log.error("Illegal Parameter: " + req.getParameterMap());
                return null;
            } catch (IOException ex) {
                log.error("error", ex);
            }
        }

        Pager<Club> pager = clubService.searchClubBy(provinceId, cityId, brandId, seriesId, themeId, pageNo, pageSize);
        WebUtils.checkPageMaxNo(resp, pageNo, pager.getPageCount());//超过最大页数，404

        List<Club> listClub = clubService.listClubByPlace(provinceId);

        List<SearchUrl> listProvince = clubService.searchProvince(brandId, seriesId, themeId);
        List<SearchUrl> listTheme = clubService.searchTheme(provinceId, cityId, brandId, seriesId);
        //查询该省下具有车友会的城市
        List<SearchUrl> listCity = clubService.searchCity(provinceId, cityId, brandId, seriesId, themeId);

        List<SearchUrl> listBrand = clubService.searchBrand(clubService.getBreadOrSeries(listClub, 0, 1), provinceId, cityId, brandId, seriesId, themeId);

        List<SearchUrl> listSeriesId = clubService.searchSeries(clubService.getBreadOrSeries(listClub, brandId, 2), provinceId, cityId, brandId, seriesId, themeId);

        //获取所有车友会品牌
        List<ClubBrand> clubBrands = clubBrandService.getAllClubBrand();
        Map<String, String> initialMap = new TreeMap<String, String>();//TreeMap默认升序排序
        //获得所有车友会品牌首字母（map去重）
        for (ClubBrand clubBrand : clubBrands) {
            initialMap.put(clubBrand.getInitial(), clubBrand.getInitial());
        }
        String base = systemConfig.getRoot() + "/all/";
        String url = base + "c";
        String allProvince = base;
        String allCity = base;
        String allBrand = base;
        String allSeries = base;
        String allTheme = base;

        if (brandId > 0 || seriesId > 0 || themeId > 0) {
            allProvince += "c";
        }
        if (provinceId > 0) {
            allCity += "c";
        }
        if (provinceId > 0 || cityId > 0 || themeId > 0) {
            allBrand += "c";
        }
        if (brandId > 0) {
            allSeries += "c";
        }
        if (provinceId > 0 || cityId > 0 || brandId > 0 || seriesId > 0) {
            allTheme += "c";
        }

        if (provinceId > 0 || cityId > 0 || brandId > 0 || seriesId > 0 || themeId > 0) {
            if (provinceId > 0) {
                url += "-p" + provinceId;
                allBrand += "-p" + provinceId;
                allCity += "-p" + provinceId;
                allSeries += "-p" + provinceId;
                allTheme += "-p" + provinceId;
            }
            if (cityId > 0 && provinceId > 0) {
                url += "-s" + cityId;
                allBrand += "-s" + cityId;
                allSeries += "-s" + cityId;
                allTheme += "-s" + cityId;
            }
            if (brandId > 0) {
                url += "-b" + brandId;
                allProvince += "-b" + brandId;
                allCity += "-b" + brandId;
                allSeries += "-b" + brandId;
                allTheme += "-b" + brandId;
            }
            if (seriesId > 0 && brandId > 0) {
                url += "-c" + seriesId;
                allProvince += "-c" + seriesId;
                allCity += "-c" + seriesId;
                allTheme += "-c" + seriesId;
            }
            if (themeId > 0) {
                url += "-z" + themeId;
                allProvince += "-z" + themeId;
                allBrand += "-z" + themeId;
                allCity += "-z" + themeId;
            }
        }
        if (!allProvince.equals(base)) {
            allProvince += ".html";
        }
        if (!allCity.equals(base)) {
            allCity += ".html";
        }
        if (!allBrand.equals(base)) {
            allBrand += ".html";
        }
        if (!allSeries.equals(base)) {
            allSeries += ".html";
        }
        if (!allTheme.equals(base)) {
            allTheme += ".html";
        }
        SearchUrl selectCity = null;
        for (SearchUrl sCity : listCity) {
            if (sCity.isIsSelect()) {
                selectCity = sCity;
            }
        }
        //取选中筛选的品牌车系,没有才根据ID查找数据库
        SearchUrl searchBrand = null;
        for (SearchUrl brand : listBrand) {
            if (brand.isIsSelect()) {
                searchBrand = brand;
            }
        }
        SearchUrl searchSeries = null;
        for (SearchUrl series : listSeriesId) {
            if (series.isIsSelect()) {
                searchSeries = series;
            }

        }
        Club bClub = null;
        if (searchBrand == null) {
            bClub = clubService.selectMenuByClub(0, brandId, 0);
        }
        Club sClub = null;
        String seriesName = "";
        if (searchSeries == null) {
            sClub = clubService.selectMenuByClub(0, 0, seriesId);
            if (sClub == null && seriesId > 0) {
                seriesName = getSeriesBySeriesId(seriesId);
            }
        }
        String themeName = "";
        Theme theme = themeService.findThemeById(themeId);
        if (theme != null) {
            themeName = theme.getThemeName();
        }

        req.setAttribute("pager", pager);
        req.setAttribute("listProvince", listProvince);
        req.setAttribute("listTheme", listTheme);
        req.setAttribute("listBrand", listBrand);
        req.setAttribute("listSeriesId", listSeriesId);
        req.setAttribute("listCity", listCity);
        req.setAttribute("thisUrl", url);
        req.setAttribute("allProvince", allProvince);
        req.setAttribute("allCity", allCity);
        req.setAttribute("allBrand", allBrand);
        req.setAttribute("allSeries", allSeries);
        req.setAttribute("allTheme", allTheme);
        req.setAttribute("proName", clubService.getNameByProvinceId(provinceId));
        req.setAttribute("braName", searchBrand == null ? (bClub == null ? "" : bClub.getBrandName()) : searchBrand.getName());
        req.setAttribute("serName", searchSeries == null ? (sClub == null ? seriesName : sClub.getSeriesName()) : searchSeries.getName());
        req.setAttribute("selectCityName", selectCity == null ? "" : selectCity.getName());
        req.setAttribute("themeName", themeName);
        req.setAttribute("initialMap", initialMap);
        req.setAttribute("clubBrands", clubBrands);
        return "/index/search";
    }

    /**
     * 活动获取用户、车友会
     *
     * @param req
     * @param resp
     */
    @ResponseBody
    @RequestMapping(value = "/club/getUserClub.do", method = RequestMethod.GET)
    public void getUserClub(HttpServletRequest req, HttpServletResponse resp) {
        String req_enc = WebUtils.param(req, "req_enc", "GBK");
        String resp_enc = WebUtils.param(req, "resp_enc", "GBK");
        try {
            req.setCharacterEncoding(req_enc);
            resp.setCharacterEncoding(resp_enc);

        } catch (UnsupportedEncodingException ex) {
            log.error("set request and response charset error.", ex);
        }
        JSONObject json = new JSONObject();
        long uid = WebUtils.paramInt(req, "uid", 0);
        String callback = WebUtils.param(req, "callback", "");
        int sourceAgent = WebUtils.paramInt(req, "source_agent", DEF_SOURCE_AGENT);
        User user;
        if (uid == 0) {
            user = userAuth.getUser(req, resp);
            uid = user.getUid();
        } else {
            user = userService.findUser(uid);
        }
        if (uid > 0) {
            JSONArray arr = new JSONArray();
            List<ClubMember> list = memberService.listClubMemberByUser(uid);
            if (list != null && !list.isEmpty()) {
                for (ClubMember cm : list) {
                    Club club = clubService.getClub(cm.getClubId());
                    ClubAddress a = clubService.getAddress(cm.getClubId());
                    JSONObject jsonObject = parseJSONObject(club, a, user, sourceAgent);
                    jsonObject.put("isVip", user.getVip());
                    jsonObject.put("vipInfo", user.getVipInfo());
                    jsonObject.put("memberId", cm.getId());
                    jsonObject.put("status", 1);
                    arr.add(jsonObject);
                }
            }
            List<MemberApplication> memberApplications = memberService.listMemberApplicationsByUserId(uid);
            for (MemberApplication m : memberApplications) {
                Club club = clubService.getClub(m.getClubId());
                ClubAddress a = clubService.getAddress(m.getClubId());
                JSONObject jsonObject = parseJSONObject(club, a, user, sourceAgent);
                jsonObject.put("isVip", user.getVip());
                jsonObject.put("vipInfo", user.getVipInfo());
                jsonObject.put("memberId", m.getId());
                jsonObject.put("status", 0);
                arr.add(jsonObject);
            }
            json.put("clubs", arr);
            json.put("code", 0);
        } else {
            json.put("code", -1);
            json.put("message", "用户没有登录或者没有传参");
        }
        print(resp, json.toJSONString(), callback);
    }
    /**
     * 没有车友会的车系缓存，减少http请求接口获取
     */
    private static final Map<Long, String> seriesIdNames = new HashMap<Long, String>();

    /**
     *
     * @Title: getSeriesBySeriesId
     * @Description: 根据车型id 到报价库接口查询车型名称
     * @param:
     * @param seriesId 车型id
     * @param:
     * @return 车型名称
     * @return: String
     * @Date 2014-9-24 下午05:17:19
     */
    public String getSeriesBySeriesId(long seriesId) {
        String seriesName = seriesIdNames.get(seriesId);
        if (StringUtils.isBlank(seriesName)) {
            String url = systemConfig.getPriceSeriesUrl() + "?serialGroupId=" + seriesId;
            String jsonString = simpleHttpTemplate.get(url, "http://club.pcauto.com.cn");
            JSONObject jsonObject = JSONObject.parseObject(jsonString);
            if (jsonObject == null) {
                return "";
            }
            seriesName = jsonObject.getString("name");
            seriesIdNames.put(seriesId, seriesName);
        }
        return seriesName;
    }

    /**
     * 实时获取短信验证码防刷KEY
     *
     * @param req
     * @param resp
     */
    @RequestMapping(value = "/club/getVCodeKey", method = RequestMethod.GET)
    public void getVCodeKey(HttpServletRequest req, HttpServletResponse resp) {
        WebUtils.setEncoding(req, resp);
        String callback = WebUtils.param(req, "callback", "");
        String Vkey = "sendVerificationCode.jsp";
        long vCodeTime = System.currentTimeMillis();
        String vCodeKey = WebUtils.md5(Vkey + vCodeTime);
        JSONObject obj = new JSONObject();
        obj.put("code", 0);
        obj.put("vCodeTime", vCodeTime);
        obj.put("vCodeKey", vCodeKey);
        print(resp, obj.toJSONString(), callback);
    }

    /**
     *
     * 获取车友会列表接口
     *
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "/club/getClubListForBBS.do", method = RequestMethod.GET)
    public void getClubListForBBS(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        WebUtils.setEncoding(req, resp);
        WebUtils.setCacheHeader(resp, 3600);//缓存 1h
        String callback = WebUtils.param(req, "callback", "");
        long cityId = WebUtils.paramInt(req, "cityId", 0);
        long provinceId = WebUtils.paramInt(req, "provinceId", 0);
        String[] seriesIds = WebUtils.paramTrim(req, "seriesIds", "").split(",");
        long brandId = WebUtils.paramInt(req, "brandId", 0);
        int pageNo = WebUtils.paramInt(req, "pageNo", 1);
        int pageSize = WebUtils.paramInt(req, "pageSize", 20, MIN_PAGESIZE, MAX_PAGESIZE);
        int sourceAgent = WebUtils.paramInt(req, "source_agent", 2);
        int themeId = WebUtils.paramInt(req, "themeId", 0);//主题ID List<Object> sids = new ArrayList<Object>(seriesIds.length);
        List<Object> sids = new ArrayList<Object>(seriesIds.length);
        for (String s : seriesIds) {
            try {
                int i = Integer.parseInt(s);
                if (i > 0) {
                    sids.add(i);
                }
            } catch (java.lang.NumberFormatException e) {
                continue;
            }
        }
        Pager<Club> pager = clubService.pageClubByPlaceId(cityId, 0, provinceId, brandId, sids.toArray(), 0, null, pageNo, pageSize, themeId);
        JSONObject json = new JSONObject();
        if (pager.getResultList() != null && !pager.getResultList().isEmpty()) {
            JSONArray jsonArray = new JSONArray();
            for (Club club : pager.getResultList()) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("clubId", club.getClubId());
                jsonObject.put("name", EncodeUtils.encodeForHTML(club.getName(), sourceAgent));
                jsonObject.put("logo", EncodeUtils.encodeForHTML(club.getLogo(), sourceAgent));
                jsonObject.put("memberSum", club.getMemberNum());
                jsonObject.put("vipSum", club.getVipNum());
                jsonObject.put("level", club.getLevelId());
                ClubLevel clubLevel = clubLevelService.getById(club.getLevelId());
                jsonObject.put("levelName", EncodeUtils.encodeForHTML(clubLevel == null ? "" : clubLevel.getLevelName(), sourceAgent));
                jsonObject.put("clubStatus", club.getStatus());
                jsonObject.put("brandId", club.getBrandId());
                jsonObject.put("rank", club.getRank());
                jsonObject.put("regionRank", club.getRegionRank());
                jsonObject.put("provinceRank", club.getProvinceRank());
                jsonObject.put("brandRank", club.getBrandRank());
                jsonObject.put("seriesName", EncodeUtils.encodeForHTML(club.getSeriesName(), sourceAgent));
                jsonObject.put("brandName", EncodeUtils.encodeForHTML(club.getBrandName(), sourceAgent));
                jsonObject.put("provinceName", EncodeUtils.encodeForHTML(club.getProvinceName(), sourceAgent));
                jsonObject.put("cityName", EncodeUtils.encodeForHTML(club.getCityName(), sourceAgent));
                jsonObject.put("introduce", EncodeUtils.encodeForHTML(club.getIntroduce(), sourceAgent));
                jsonObject.put("qqGroup", club.getQqGroup());
                jsonObject.put("clubUrl", club.getClubUrl());
                //根据clubId得到活跃度值
                ClubStat clubStat = statService.getClubStatByClubId(club.getClubId());
                if (clubStat != null) {
                    jsonObject.put("rankPetrol", clubStat.getRankPetrol());
                } else {
                    jsonObject.put("rankPetrol", "");
                }
                jsonArray.add(jsonObject);
            }
            AppUtils.setSuccessCode(json);
            json.put("data", jsonArray);
            json.put("total", pager.getTotal());
            json.put("pageNo", pager.getPageNo());
            json.put("pageCount", pager.getPageCount());
            json.put("pageSize", pager.getPageSize());
        } else {
            json.put("data", new JSONArray());
            AppUtils.setSuccessCode(json);
        }
        try {
            PrintWriter print = resp.getWriter();
            if (StringUtils.isNotBlank(callback)) {
                print.println(EncodeUtils.encodeForHTML(callback, 2) + "(" + json.toJSONString() + ")");
            } else {
                print.println(json.toJSONString());
            }
            print.flush();
            print.close();
        } catch (IOException ex) {
            log.error("error", ex);
        }
    }

    /**
     * 车友会平台介绍页（默认动态展示前9个车友会及相关信息）规则跟搜索页一样
     *
     * @param req
     * @param resp
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "/1.0/club/getExcellentClub.do")
    public void getExcellentClub(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        WebUtils.setEncoding(req, resp);
        WebUtils.setCacheHeader(resp, 3600);//缓存 1h
        String callback = WebUtils.param(req, "callback", "");
        int pageNo = WebUtils.paramInt(req, "pageNo", 1);
        int pageSize = WebUtils.paramInt(req, "pageSize", 9, MIN_PAGESIZE, MAX_PAGESIZE);
        int xssEncode = WebUtils.paramInt(req, AppControllerStatic.APP_API_PARA_XSSENCODE, 1);
        JSONObject json = new JSONObject();
        Pager<Club> pager = clubService.searchClubBy(0, 0, 0, 0, 0, pageNo, pageSize);
        if (pager.getResultList() != null && !pager.getResultList().isEmpty()) {
            JSONArray jsonArray = new JSONArray();
            for (Club club : pager.getResultList()) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("logo", xssEncode > 0 ? EncodeUtils.encodeForHTMLFilterNull(club.getLogo()) : club.getLogo());
                jsonObject.put("name", xssEncode > 0 ? EncodeUtils.encodeForHTMLFilterNull(club.getName()) : club.getName());
                jsonObject.put("seriesName", xssEncode > 0 ? EncodeUtils.encodeForHTMLFilterNull(club.getSeriesName()) : club.getSeriesName());
                jsonObject.put("brandName", xssEncode > 0 ? EncodeUtils.encodeForHTMLFilterNull(club.getBrandName()) : club.getBrandName());
                jsonObject.put("provinceName", xssEncode > 0 ? EncodeUtils.encodeForHTMLFilterNull(club.getProvinceName()) : club.getProvinceName());
                jsonObject.put("cityName", xssEncode > 0 ? EncodeUtils.encodeForHTMLFilterNull(club.getCityName()) : club.getCityName());
                jsonObject.put("memberSum", club.getMemberNum());
                jsonObject.put("vipSum", club.getVipNum());
                jsonObject.put("level", club.getLevelId());
                jsonObject.put("clubUrl", systemConfig.getRoot() + "/" + club.getClubUrl() + "/");
                jsonArray.add(jsonObject);
            }
            AppUtils.setSuccessCode(json);
            json.put("version", AppUtils.V1_VERSION_LATEST);
            json.put("data", jsonArray);
            json.put("total", pager.getTotal());
            json.put("pageNo", pager.getPageNo());
            json.put("pageCount", pager.getPageCount());
            json.put("pageSize", pager.getPageSize());

        } else {
            json.put("data", new JSONArray());
            AppUtils.setSuccessCode(json);
        }
        try {
            PrintWriter print = resp.getWriter();
            if (StringUtils.isNotBlank(callback)) {
                print.println(EncodeUtils.encodeForHTMLFilterNull(callback) + "(" + json.toJSONString() + ")");
            } else {
                print.println(json.toJSONString());
            }
            print.flush();
            print.close();
        } catch (IOException ex) {
            log.error("error", ex);
        }
    }

    /**
     * 一键邀请
     *
     * @param request
     * @param model
     * @param resp
     * @return
     */
    @RequestMapping(value = "/club/createInviteLink.do", method = RequestMethod.GET)
    public void createInviteLink(HttpServletRequest request, Model model, HttpServletResponse resp) {
        WebUtils.setEncoding(request, resp);
        User user = checkAndSetUser(request, resp);
        if (user == null || user.getUid() <= 0) {
            printErrorMsg(resp, "请先登录", null);
            return;
        }
        long clubId = WebUtils.paramLong(request, "clubId", 0);
        Club club = clubService.getValidClub(clubId);
        if (club == null) {
            printErrorMsg(resp, "找不到该车友会", null);
            return;
        }
        if (!memberService.isClubMember(user.getUid(), clubId)) {
            printErrorMsg(resp, "只有该车友会成员才能操作", null);
            return;
        }

        int day = InviteJoin.INVITE_VALID_DAY;
        Date currentDate = DateUtils.getNow();
        Date overdueAt = DateUtils.getDateAfter(currentDate, day);
        InviteJoin inviteJoin = new InviteJoin();
        String key = currentDate.getTime() + "_" + clubId;
        String shortUrl = ShortUrlUtil.shortUrl(key);
        inviteJoin.setClubId(clubId);
        inviteJoin.setCreateBy(user.getUid());
        inviteJoin.setCreateAt(currentDate);
        inviteJoin.setOverdueAt(overdueAt);
        inviteJoin.setInvitedCount(0);
        inviteJoin.setInviteCode(shortUrl);
        long id = inviteJoinService.createInviteJoin(inviteJoin);
        if (id == 0) {
            printErrorMsg(resp, "获取邀请URL失败", null);
            return;
        }
        JSONObject obj = new JSONObject();
        obj.put("status", JsonResult.STATUS_SUCCESS);
        obj.put("clubName", club.getName());
        obj.put("inviteUrl", systemConfig.getRoot() + "/" + club.getClubUrl() + "/invite/" + inviteJoin.getInviteCode());
        print(resp, obj.toJSONString(), null);
    }

    /**
     * 打开一键邀请
     *
     * @param request
     * @param model
     * @param resp
     * @return
     */
    @RequestMapping(value = "/club/getInviteLink.do", method = RequestMethod.GET)
    public String getInviteLink(HttpServletRequest request, Model model, HttpServletResponse resp) {
        String inviteCode = WebUtils.paramTrim(request, "code", "");
        String desc = WebUtils.paramTrim(request, "desc", "");
        request.setAttribute("code", inviteCode);
        request.setAttribute("desc", desc);
        request.setAttribute("type", "getInviteLink");
        if (StringUtils.isBlank(inviteCode)) {
            try {
                resp.sendError(404);
                return null;
            } catch (IOException ex) {
                log.error("error", ex);
            }
        }
        InviteJoin inviteJoin = inviteJoinService.getAllInviteJoinByCode(inviteCode);
        Club club;
        if (inviteJoin == null) {
            request.setAttribute("msg", "该邀请链接不存在");
            request.setAttribute("isInviteError", true);
            return "/template/club/common/errorPop";
        } else if (inviteJoin.isOverdue()) {
            request.setAttribute("msg", "该邀请链接已过期");
            request.setAttribute("isFail", true);
            club = clubService.getValidClub(inviteJoin.getClubId());
            if (club != null) {
                User user = userService.findUser(club.getAdminId());
                request.setAttribute("user", user);
            }
            request.setAttribute("club", club);
            request.setAttribute("isInviteError", true);
            return "/template/club/common/errorPop";
        }
        long adminId = inviteJoin.getCreateBy();
        User user = userService.findUser(adminId);
        club = clubService.getValidClub(inviteJoin.getClubId());
        ClubMember inviteUser = memberService.findMember(inviteJoin.getCreateBy(), club.getClubId());
        if (club == null || user == null || inviteUser == null) {
            request.setAttribute("msg", "该邀请链接已失效");
            request.setAttribute("isInviteError", true);
            return "/template/club/common/errorPop";
        }
        int count = memberService.countMembersByClubId(club.getClubId());
        List<ClubMember> lastestMembers = memberService.getLastestMember(club.getClubId(), DISPLAY_LASTEST_COUNT);
        userService.loadTransientUsers(lastestMembers);
        request.setAttribute("members", lastestMembers);
        request.setAttribute("count", count);
        request.setAttribute("user", user);
        request.setAttribute("club", club);
        request.setAttribute("inviteJoin", inviteJoin);
        return "/template/club/invite";
    }

    /**
     * 创建车友会第一步(创建草稿)
     *
     * @param request
     * @param resp
     */
    @RequestMapping(value = "/club/applyCreateClubDraft.do", method = RequestMethod.POST)
    public void applyCreateClubDraft(HttpServletRequest request, HttpServletResponse resp) {
        WebUtils.setEncoding(request, resp);
        //当该方法返回null的时候证明没登录,提示信息已经在checkAndSetUser返回, 只有在POST接口有效
        if (checkAndSetUser(request, resp) == null) {
            return;
        }
        User user = userAuth.getUser(request, resp);
        /**
         * 检查车友会信息并组装车友会草稿*
         */
        ClubDraft clubDraft = assemblingAndCheckClubInfo(request, resp, user);
        if (clubDraft == null) {
            return;
        }
        //验证是否可以创建车友会
        String msg = checkJoinedClub(user);
        if (!StringUtils.isBlank(msg)) {
            errorMsg(resp, msg, null);
            return;
        }
        int count = clubDraftService.createOrUpdate(clubDraft);
        if (count > 0) {
            successMsg(resp, "申请成功");
        } else {
            errorMsg(resp, "申请失败", null);
        }
    }

    /**
     * 创建第二步页面跳转
     *
     * @param request
     * @param resp
     * @return
     */
    @RequestMapping(value = "/club/applyCreateClubUserInfoForPage.do", method = RequestMethod.GET)
    public String applyCreateClubForAddress(HttpServletRequest request, HttpServletResponse resp) {
        //当该方法返回null的时候证明没登录,提示信息已经在checkAndSetUser返回, 只有在POST接口有效
        User user = checkAndSetUser(request, resp);
        if (user == null) {
            return null;
        }
        //验证是否可以创建车友会
        String msg = checkJoinedClub(user);
        if (!StringUtils.isBlank(msg)) {
            request.setAttribute("msg", msg);
            return "/template/club/common/errorPop";
        }
        ClubDraft clubDraft = clubDraftService.findDraftByUserId(user.getUid());
        if (clubDraft == null) {
            request.setAttribute("msg", "请一步一步填写,先填写车友会信息!");
            return "/template/club/foundFail";
        }
        return "template/club/foundUserInfo";
    }

    /**
     * 创建车友会第二步(保存车友会地址和生成车友会记录)
     *
     * @param request
     * @param resp
     */
    @RequestMapping(value = "/club/applyCreateClubForUserInfo.do", method = RequestMethod.POST)
    public void applyCreateClub(HttpServletRequest request, HttpServletResponse resp) {
        WebUtils.setEncoding(request, resp);
        //当该方法返回null的时候证明没登录,提示信息已经在checkAndSetUser返回, 只有在POST接口有效
        User user = checkAndSetUser(request, resp);
        if (user == null) {
            return;
        }
        String realName = WebUtils.param(request, "name", "");
        if (StringUtils.isBlank(realName)) {
            errorMsg(resp, "真实姓名不能为空", "name");
            return;
        }
        if (!realName.matches("([\\u4e00-\\u9fa5])*")) {
            errorMsg(resp, "请输入您的中文真实姓名", "name");
            return;
        }
        String address = WebUtils.param(request, "address", "");
        String phone = WebUtils.param(request, "phone", "");
        if (StringUtils.isBlank(phone)) {
            errorMsg(resp, "手机号码不能为空", "phone");
            return;
        }
        if (!phone.matches(Regex.cellphone.value)
                || phone.matches(Regex.specialPhone.value)) {
            errorMsg(resp, "请填写合法的手机", "phone");
            return;
        }
        String code = WebUtils.paramTrim(request, "code", "");
        if (StringUtils.isBlank(code)) {
            errorMsg(resp, "请输入验证码", "code");
            return;
        }
        if (systemConfig.isNeedCheckCode()) {
            String checkCodeMsg = checkPhoneCode(phone, code);
            if (StringUtils.isNotEmpty(checkCodeMsg)) {
                errorMsg(resp, checkCodeMsg, "code");
                return;
            }
        }
        String postCode = WebUtils.param(request, "postCode", "");
        long cityId = WebUtils.paramLong(request, "cityId", 0);
        String cityName = WebUtils.getAreaPlaceByReq(request, "cityName", "");
        int sex = WebUtils.paramInt(request, "sex", User.CLUB_MALE);
        long provinceId = WebUtils.paramLong(request, "provinceId", 0);
        String provinceName = WebUtils.param(request, "provinceName", "");
        //验证是否可以创建车友会
        String msg = checkJoinedClub(user);
        if (!StringUtils.isBlank(msg)) {
            errorMsg(resp, msg, null);
            return;
        }
        ClubDraft clubDraft = clubDraftService.findDraftByUserId(user.getUid());
        if (clubDraft != null) {
            Club club = clubDraftService.parseClubDraftToClub(clubDraft);
            if (club != null) {
                ClubAddress clubAddress = new ClubAddress();
                clubAddress.setAddress(address);
                clubAddress.setClubId(club.getClubId());
                clubAddress.setName(realName);
                clubAddress.setPhone(phone);
                clubAddress.setPostcode(postCode);
                clubAddress.setUpdateAt(new Date());
                //地区ID
                long domicileId = 0;
                if (provinceId > 0 && cityId > 0) {
                    domicileId = cityId;
                    clubAddress.setCityId(cityId);
                    clubAddress.setProvinceId(provinceId);
                    clubAddress.setCityName(cityName);
                    clubAddress.setProvinceName(provinceName);
                } else {//没选地区时置空
                    clubAddress.setCityId(0);
                    clubAddress.setProvinceId(0);
                    clubAddress.setCityName("");
                    clubAddress.setProvinceName("");
                }
                long clubId = clubService.create(club, clubAddress);
                clubDraftService.deleteClubDraft(clubDraft);

                //保存个人资料到ac_user
                user.setTruename(realName);
                user.setPhone(phone);
                user.setGender(sex);
                //地区ID
                if (provinceId > 0 && cityId > 0) {
                    user.setCityId(cityId);
                    user.setProvinceId(provinceId);
                    user.setCity(cityName);
                    user.setProvince(provinceName);
                } else {//没选地区时置空
                    user.setCityId(0);
                    user.setProvinceId(0);
                    user.setCity("");
                    user.setProvince("");
                }
                userService.updateUser(user);

                if (clubId > 0) {
                    //同步个人信息到个人中心
                    String commonSessionId = cn.pconline.passport2.util.WebUtils.getCookie(request, systemConfig.getUserSessionName());
                    intfService.updateUserCenter(commonSessionId, realName, null, sex, phone, postCode, address, domicileId, null);
                    successMsg(resp, "创建成功");
                } else {
                    errorMsg(resp, "创建失败", "");
                }
            }
        } else {
            errorMsg(resp, "用户ID错误", "");
        }
    }

    /**
     * 校验车友会信息
     *
     * @param club
     * @param resp
     * @return
     */
    private boolean checkClubInfo(Club club, HttpServletResponse resp) {
        String retNameMsg = clubService.checkClubName(club.getName());
        if (!"true".equals(retNameMsg)) {
            errorMsg(resp, retNameMsg, "name");
            return false;
        }
        String retUrlMsg = clubService.checkClubUrl(club.getClubUrl());
        if (!"true".equals(retUrlMsg)) {
            errorMsg(resp, retUrlMsg, "clubUrl");
            return false;
        }
        if (club.getProvinceId() != 0 && StringUtils.isBlank(club.getProvinceName())) {
            errorMsg(resp, "缺少省份名称", "");
            return false;
        } else if (club.getProvinceName().length() > INPUT_MAX_LENGTH) {
            errorMsg(resp, "非法省份名称", "");
            return false;
        }
        if (club.getCityId() != 0 && StringUtils.isBlank(club.getCityName())) {
            errorMsg(resp, "缺少城市名称", "");
            return false;
        } else if (club.getCityName().length() > INPUT_MAX_LENGTH) {
            errorMsg(resp, "非法城市名称", "");
            return false;
        }
        if (club.getBrandId() != 0 && StringUtils.isBlank(club.getBrandName())) {
            errorMsg(resp, "缺少品牌名称", "");
            return false;
        } else if (club.getBrandName() != null && club.getBrandName().length() > INPUT_MAX_LENGTH) {
            errorMsg(resp, "非法品牌名称", "");
            return false;
        }
        if (club.getSeriesId() != 0 && StringUtils.isBlank(club.getSeriesName())) {
            errorMsg(resp, "缺少车系名称", "");
            return false;
        } else if (club.getSeriesName().length() > INPUT_MAX_LENGTH) {
            errorMsg(resp, "非法车系名称", "");
            return false;
        }
        if (club.getProvinceId() == 0 && club.getCityId() != 0) {//非法操作
            errorMsg(resp, "缺少省份", "cityId");
            return false;
        }
        if (club.getBrandId() == 0 && club.getSeriesId() != 0) {//非法操作
            errorMsg(resp, "缺少品牌", "seriesId");
            return false;
        }
        if (club.getType() == Club.TYPE_AREA) {//
            if (club.getProvinceId() == 0) {//允许只选省份
                errorMsg(resp, "请选择地区", "cityId");
                return false;
            }
        } else if (club.getType() == Club.TYPE_SERIAL) {
            if (club.getBrandId() == 0) {//允许只选品牌
                errorMsg(resp, "请选择品牌/车系", "seriesId");
                return false;
            }
        } else if (club.getType() == Club.TYPE_THEME) {
            if (club.getThemeId() == 0) {
                errorMsg(resp, "请选择主题", "themeId");
                return false;
            }
        } else {
            errorMsg(resp, "请选择车友会类型", "clubType");
            return false;
        }
        String qqGroupMsg = clubService.checkClubQQGroup(club.getQqGroup());
        if (!"true".equals(qqGroupMsg)) {
            errorMsg(resp, qqGroupMsg, "qqGroup");
            return false;
        }
        return true;
    }

    /**
     * 组装车友会信息
     *
     * @param request
     * @param user
     * @return
     */
    private Club assemblingClub(HttpServletRequest request, User user) {
        //param
        String name = WebUtils.paramTrim(request, "name", "");
        String clubUrl = WebUtils.paramTrim(request, "clubUrl", "").replaceAll(" ", "").toLowerCase();
        long themeId = WebUtils.paramLong(request, "themeId", 0);
        int clubType = WebUtils.paramInt(request, "clubType", -1);
        long provinceId = WebUtils.paramLong(request, "provinceId", 0);
        String provinceName = WebUtils.paramTrim(request, "provinceName", "");
        long cityId = WebUtils.paramLong(request, "cityId", 0);
        String cityName = WebUtils.getAreaPlaceByReq(request, "cityName", "");
        long brandId = WebUtils.paramLong(request, "brandId", 0);
        String brandName = WebUtils.getAreaPlaceByReq(request, "brandName", "");
        long seriesId = WebUtils.paramLong(request, "seriesId", 0);
        String seriesName = WebUtils.paramTrim(request, "seriesName", "");
        String qqGroup = WebUtils.paramTrim(request, "qqGroup", "");
        long regionId = RegionUtil.getRegionId(provinceId);
        String regionName = RegionUtil.getRegionName(regionId);
        Date currentDate = new Date();
        Club club = new Club();
        club.setType(clubType);
        club.setAdminId(user.getUid());
        club.setAuditAt(null);
        club.setAuditBy(0);
        club.setThemeId(themeId);
        club.setBrandId(brandId);
        club.setCityId(cityId);
        club.setCityName(cityName);
        club.setCreateAt(currentDate);
        club.setCreateBy(user.getUid());
        club.setIntroduce("");
        club.setLevelId(0);
        club.setLogo("");
        club.setMemberNum(0);
        club.setName(name);
        club.setProvinceId(provinceId);
        club.setProvinceName(provinceName);
        club.setRegionId(regionId);
        club.setRegionName(regionName);
        club.setReplyNum(0);
        club.setSeriesId(seriesId);
        club.setSeriesName(seriesName);
        club.setStatus(Club.STATUS_UNAUDITED);
        club.setTopicNum(0);
        club.setUpdateAt(currentDate);
        club.setUpdateBy(user.getUid());
        club.setVipNum(0);
        club.setClubUrl(clubUrl);
        club.setQqGroup(qqGroup);
        if (StringUtils.isNotBlank(brandName)) {
            club.setBrandName(brandName.substring(2, brandName.length()));
        }
        if (club.getType() == Club.TYPE_AREA) {//
            //选了地区，其他不必填
            club.setThemeId(0);
            club.setBrandId(0);
            club.setBrandName("");
            club.setSeriesId(0);
            club.setSeriesName("");
        } else if (club.getType() == Club.TYPE_SERIAL) {
            //选了品牌/车系，主题不必填
            club.setThemeId(0);
        }
        return club;
    }

    /**
     * 组装车友会草稿并检查车友会信息
     *
     * @param request
     * @param resp
     * @param user
     * @return
     */
    private ClubDraft assemblingAndCheckClubInfo(HttpServletRequest request, HttpServletResponse resp, User user) {
        Club club = assemblingClub(request, user);
        if (!checkClubInfo(club, resp)) {
            return null;
        }
        //创建车友会草稿
        ClubDraft clubDraft = clubDraftService.parseClubToClubDraft(club);
        return clubDraft;
    }

    /**
     * 一键邀请(个人信息)
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/club/inviteJoin.do")
    public String inviteJoin(HttpServletRequest req, HttpServletResponse resp) {
        String code = WebUtils.param(req, "code", "");
        req.setAttribute("code", code);
        req.setAttribute("type", "inviteJoin");
        if (StringUtils.isBlank(code)) {
            try {
                resp.sendError(404);
                return null;
            } catch (IOException ex) {
                log.error("error", ex);
            }
            return null;
        }

        InviteJoin inviteJoin = inviteJoinService.getAllInviteJoinByCode(code);
        Club club;
        if (inviteJoin == null) {
            req.setAttribute("msg", "该邀请链接不存在");
            req.setAttribute("isInviteError", true);
            return "template/club/common/errorPop";
        } else if (inviteJoin.isOverdue()) { //是否过期
            req.setAttribute("msg", "该邀请链接已过期");
            req.setAttribute("isFail", true);
            club = clubService.getValidClub(inviteJoin.getClubId());
            if (club != null) {
                User adminUser = userService.findUser(club.getAdminId());
                req.setAttribute("user", adminUser);
            }
            req.setAttribute("club", club);
            req.setAttribute("isInviteError", true);
            return "template/club/common/errorPop";
        }
        
        club = clubService.getValidClub(inviteJoin.getClubId());
        if (club == null) {
            req.setAttribute("msg", "该车友会不存在");
            req.setAttribute("isInviteError", true);
            return "template/club/common/errorPop";
        }
        
        ClubMember inviteUser = memberService.findMember(inviteJoin.getCreateBy(), club.getClubId());
        if(inviteUser == null) {
             req.setAttribute("msg", "该邀请链接已失效");
             req.setAttribute("isInviteError", true);
             return "template/club/common/errorPop";
        }
        req.setAttribute("isAdmin", inviteUser.isAdministrator());
        
        User user = userAuth.getUser(req, resp);
        if (user == null || user.getUid() == 0) {
            req.setAttribute("PASSPORT", systemConfig.getPassportRoot());
            req.setAttribute("returnUrl", systemConfig.getRoot() + "/invite/info/" + code + "/");
            req.setAttribute("code", code);
            return "template/club/inviteLogin";
        }
        
        if (memberService.isClubMember(user.getUid(), club.getClubId())) {
            req.setAttribute("msg", "已经加入该车友会");
            req.setAttribute("isInviteError", true);
            return "template/club/common/errorPop";
        }
        //验证加入车友会个数
        int count = userService.updateJoinedClubCount(user);
        if (count >= NumberUtils.toInt(systemConfig.getJoinClubLimit(), 1)) {
            req.setAttribute("msg", "已经加入其他车友会,无法再加入该车友会");
            req.setAttribute("isJoin", true);
            ClubMember clubMember = memberService.findClubMemberByUserId(user.getUid());
            if (clubMember != null) {
                req.setAttribute("club", clubService.getValidClub(clubMember.getClubId()));
            }
            req.setAttribute("isInviteError", true);
            return "template/club/common/errorPop";
        }
        if (!memberService.findMemberApplication(user.getUid(), club.getClubId(), true).isEmpty()) {
            req.setAttribute("msg", "您已经提交申请加入，请等待会长审核");
            req.setAttribute("isInviteError", true);
            return "template/club/common/errorPop";
        }
        if (!memberService.listClubMemberByUser(user.getUid()).isEmpty() || !clubService.findByFounder(user.getUid(), true).isEmpty()) { //已经申请加入另一个车友会 或 已创建一个车友会待审核
            req.setAttribute("msg", "您只能申请或加入一个车友会");
            req.setAttribute("isInviteError", true);
            return "template/club/common/errorPop";
        }
        
        req.setAttribute("user", user);
        req.setAttribute("clubId", club.getClubId());
        req.setAttribute("code", inviteJoin.getInviteCode());
        return "template/club/inviteUserInfo";
    }

    /**
     * 查询新增认证人数排行
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/club/listTopByVipNum.do", method = RequestMethod.GET)
    public void listTopByVipNum(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setCacheHeader(response, 1800);//缓存半小时
        WebUtils.setEncoding(request, response);
        String callback = WebUtils.param(request, "callback", "");
        JSONObject json = new JSONObject();
        JSONArray arr = new JSONArray();
        long userId = WebUtils.paramLong(request, "userId", 0);
        int sourceAgent = WebUtils.paramInt(request, "source_agent", DEF_SOURCE_AGENT);
        int source = WebUtils.paramInt(request, "source", 1);
        User user = userService.findUser(userId);
        ClubMember clubMember = null;
        Club club;
        List<MemberApplication> memberApplications = null;
        if (user != null && user.getUid() > 0) {
            memberApplications = memberService.listMemberApplicationsByUserId(user.getUid());
            // 如果此用户已经加入车友会,返回车友会全国，车系，地区排名
            clubMember = memberService.findClubMemberByUserId(user.getUid());
            if (clubMember != null) {
                club = clubService.getClub(clubMember.getClubId());
                json = getClubRank(clubMember, club);
            }
        }
        List<ClubTotalMember> list = statService.listClubMemberNumWeekly(10, 1);
        for (ClubTotalMember ctm : list) {
            Club c = clubService.getClub(ctm.getClubId());
            JSONObject obj = clubService.setTopClub2Json(c, sourceAgent);
            obj.put("weekVipNum", ctm.getWeekVipTotal() - ctm.getLastWeekVipTotal());
            Map<String, Object> map = clubService.getAdminTypeAndIdByMember(clubMember, memberApplications, c);
            int adminType = (Integer) map.get("adminType");
            obj.put("adminType", adminType);
            if (adminType > -1) {
                obj.put("isCheck", checkInService.isCheckInToday(user.getUid(), c.getClubId()));
            } else {
                obj.put("isCheck", false);
            }
            arr.add(obj);
        }
        if (source == 2) {
            json.put("dataStart", DateUtils.format(DateUtils.getLastWeekStart()).replaceAll("-", "."));
            json.put("dataEnd", DateUtils.format(DateUtils.getLastWeekEnd()).replaceAll("-", "."));
        } else {
            json.put("dataStart", DateUtils.getLastWeekStart());
            json.put("dataEnd", DateUtils.getLastWeekEnd());
        }
        json.put("data", arr);
        print(response, json.toJSONString(), callback);
    }

    /**
     * 根据新增的油值查询排行
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/club/listTopByPetrol.do", method = RequestMethod.GET)
    public void listTopByPetrol(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setCacheHeader(response, 1800);//缓存半小时
        WebUtils.setEncoding(request, response);
        String callback = WebUtils.param(request, "callback", "");
        JSONObject json = new JSONObject();
        JSONArray arr = new JSONArray();
        long userId = WebUtils.paramLong(request, "userId", 0);
        int sourceAgent = WebUtils.paramInt(request, "source_agent", DEF_SOURCE_AGENT);
        long cityId = WebUtils.paramInt(request, "cityId", 0);
        long provinceId = WebUtils.paramInt(request, "provinceId", 0);
        long seriesId = WebUtils.paramInt(request, "seriesId", 0);
        long brandId = WebUtils.paramInt(request, "brand", 0);
        int source = WebUtils.paramInt(request, "source", 1);
        User user = userService.findUser(userId);
        ClubMember clubMember = null;
        Club club;
        List<MemberApplication> memberApplications = null;
        if (user != null && user.getUid() > 0) {
            memberApplications = memberService.listMemberApplicationsByUserId(user.getUid());
            // 如果此用户已经加入车友会,返回车友会全国，车系，地区排名
            clubMember = memberService.findClubMemberByUserId(user.getUid());
            if (clubMember != null) {
                club = clubService.getClub(clubMember.getClubId());
                json = getClubRank(clubMember, club);
            }
        }
        List<ClubStat> list = statService.getClubWeekPetrolTop(10, provinceId, cityId, brandId, seriesId);
        for (ClubStat cs : list) {
            Club c = clubService.getClub(cs.getClubId());
            JSONObject obj = clubService.setTopClub2Json(c, sourceAgent);
            obj.put("weekPetrol", cs.getWeekPetrol());
            Map<String, Object> map = clubService.getAdminTypeAndIdByMember(clubMember, memberApplications, c);
            int adminType = (Integer) map.get("adminType");
            obj.put("adminType", adminType);
            if (adminType > -1) {
                obj.put("isCheck", checkInService.isCheckInToday(user.getUid(), c.getClubId()));
            } else {
                obj.put("isCheck", false);
            }
            arr.add(obj);
        }
        if (source == 2) {
            json.put("dataStart", DateUtils.format(DateUtils.getLastWeekStart()).replaceAll("-", "."));
            json.put("dataEnd", DateUtils.format(DateUtils.getLastWeekEnd()).replaceAll("-", "."));
        } else {
            json.put("dataStart", DateUtils.getLastWeekStart());
            json.put("dataEnd", DateUtils.getLastWeekEnd());
        }
        json.put("data", arr);
        print(response, json.toJSONString(), callback);
    }

    /**
     * 查询全国排行
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/club/listTopByRank.do", method = RequestMethod.GET)
    public void listTopByRank(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setCacheHeader(response, 1800);//缓存半小时
        WebUtils.setEncoding(request, response);
        String callback = WebUtils.param(request, "callback", "");
        JSONObject json = new JSONObject();
        JSONArray arr = new JSONArray();
        JSONArray arrIndex = new JSONArray();//用于保存本车友会排名前后2名的信息
        int source = WebUtils.paramInt(request, "source", 1);
        int sourceAgent = WebUtils.paramInt(request, "source_agent", DEF_SOURCE_AGENT);
        long userId = WebUtils.paramLong(request, "userId", 0);
        //是否需要返回后面数组，用于首页排行榜是否有变化显示，0则返回，1只返回排名变化
        int showType = WebUtils.paramInt(request, "showType", 0);
        User user = userService.findUser(userId);
        if (source == 2) {
            json.put("dataStart", DateUtils.format(DateUtils.getLastWeekStart()).replaceAll("-", "."));
            json.put("dataEnd", DateUtils.format(DateUtils.getLastWeekEnd()).replaceAll("-", "."));
        } else {
            json.put("dataStart", DateUtils.getLastWeekStart());
            json.put("dataEnd", DateUtils.getLastWeekEnd());
        }
        ClubMember clubMember = null;
        Club joinClub = null;
        List<MemberApplication> memberApplications = null;
        if (user != null && user.getUid() > 0) {
            memberApplications = memberService.listMemberApplicationsByUserId(user.getUid());
            // 如果此用户已经加入车友会,返回车友会全国，车系，地区排名
            clubMember = memberService.findClubMemberByUserId(user.getUid());
            if (clubMember != null) {
                joinClub = clubService.getClub(clubMember.getClubId());
            }
            json = getClubRank(clubMember, joinClub);
        }
        // 获取前20名
        List<Club> list = clubService.listClubBySortForList(ClubService.SORT_COUNTRY_TYPE, PAGE_NUM, PAGE_SIZE, 0L, 0L, 0, 0);
        for (Club club : list) {
            JSONObject obj = clubService.setTopClub2Json(club, sourceAgent);
            Map<String, Object> map = clubService.getAdminTypeAndIdByMember(clubMember, memberApplications, club);
            int adminType = (Integer) map.get("adminType");
            obj.put("adminType", adminType);
            if (adminType > -1) {
                obj.put("isCheck", checkInService.isCheckInToday(user.getUid(), club.getClubId()));
            } else {
                obj.put("isCheck", false);
            }
            arr.add(obj);
        }
        // 获取本车友会排名的前后2名
        if (joinClub != null && joinClub.getRank() > 0L) {
            int beginRank = joinClub.getRank() - 2 <= 0 ? 1 : joinClub.getRank() - 2;
            int endRank = joinClub.getRank() + 2;
            List<Club> list5Clubs = clubService.listClubBySortForList(ClubService.SORT_COUNTRY_TYPE,
                    PAGE_NUM, PAGE_SIZE, 0L, 0L, beginRank, endRank);
            for (Club club : list5Clubs) {
                JSONObject obj = clubService.setTopClub2Json(club, sourceAgent);
                Map<String, Object> map = clubService.getAdminTypeAndIdByMember(clubMember, memberApplications, club);
                int adminType = (Integer) map.get("adminType");
                obj.put("adminType", adminType);
                if (adminType > -1) {
                    obj.put("isCheck", checkInService.isCheckInToday(user.getUid(), club.getClubId()));
                } else {
                    obj.put("isCheck", false);
                }
                arrIndex.add(obj);
            }
        }
        json.put("data", arr);
        json.put("clubIndexData", arrIndex);
        print(response, json.toJSONString(), callback);
    }

    /**
     * 组装车友会排名信息JSONObject对象
     *
     * @param clubMember
     * @param club
     * @return
     */
    private JSONObject getClubRank(ClubMember clubMember, Club club) {
        JSONObject json = new JSONObject();
        if (clubMember != null && club != null) {
            json.put("rank", club.getRank());
            //如果昨天的全国排名为0，不参与排名升降比较
            json.put("rankAsc", club.getDayRank() == 0 ? 0 : club.getDayRank() - club.getRank());
            json.put("brandRank", club.getBrandRank());
            //如果昨天的品牌排名为0，不参与排名升降比较
            json.put("brandRankAsc", club.getDayBrandRank() == 0 ? 0 : club.getDayBrandRank() - club.getBrandRank());
            json.put("provinceRank", club.getProvinceRank());
            //如果昨天的地区排名为0，不参与排名升降比较
            json.put("provinceRankAsc", club.getDayProvinceRank() == 0 ? 0 : club.getDayProvinceRank() - club.getProvinceRank());
        }
        return json;
    }

    /**
     * 获取车系排名
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/club/listTopForSeries.do", method = RequestMethod.GET)
    public void listTopForSeries(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setCacheHeader(response, 1800);//缓存半小时
        WebUtils.setEncoding(request, response);
        String callback = WebUtils.param(request, "callback", "");
        JSONObject json = new JSONObject();
        JSONArray arr = new JSONArray();
        JSONArray arrIndex = new JSONArray();//用于保存本车友会排名前后2名的信息
        int source = WebUtils.paramInt(request, "source", 1);
        int sourceAgent = WebUtils.paramInt(request, "source_agent", DEF_SOURCE_AGENT);
        long userId = WebUtils.paramLong(request, "userId", 0);
        //是否需要返回后面数组，用于首页排行榜是否有变化显示，0则返回，1只返回排名变化
        int showType = WebUtils.paramInt(request, "showType", 0);
        User user = userService.findUser(userId);
        ClubMember clubMember = null;
        Club club = null;
        List<MemberApplication> memberApplications = null;
        if (user != null && user.getUid() > 0) {
            clubMember = memberService.findClubMemberByUserId(user.getUid());
            memberApplications = memberService.listMemberApplicationsByUserId(user.getUid());
            // 如果此用户已经加入车友会,返回车友会全国，车系，地区排名
            if (clubMember != null) {
                club = clubService.getClub(clubMember.getClubId());
                json = getClubRank(clubMember, club);
            }
        }
        // 获取前20名
        long brandIdByClub = club == null ? 0 : club.getBrandId();
        if (brandIdByClub > 0) {
            List<Club> list = clubService.listClubBySortForList(ClubService.SORT_SERIES_TYPE, PAGE_NUM, PAGE_SIZE,
                    brandIdByClub, 0L, 0, 0);
            for (Club c : list) {
                JSONObject obj = clubService.setTopClub2Json(c, sourceAgent);
                Map<String, Object> map = clubService.getAdminTypeAndIdByMember(clubMember, memberApplications, c);
                int adminType = (Integer) map.get("adminType");
                obj.put("adminType", adminType);
                if (adminType > -1) {
                    obj.put("isCheck", checkInService.isCheckInToday(user.getUid(), c.getClubId()));
                } else {
                    obj.put("isCheck", false);
                }
                arr.add(obj);
            }
            // 获取本车友会排名的前后2名
            if (club != null && club.getBrandRank() > 0L) {
                int beginRank = club.getBrandRank() - 2 <= 0 ? 1 : club.getBrandRank() - 2;
                int endRank = club.getBrandRank() + 2;
                List<Club> list5Clubs = clubService.listClubBySortForList(ClubService.SORT_SERIES_TYPE, PAGE_NUM, PAGE_SIZE,
                        brandIdByClub, 0L, beginRank, endRank);
                for (Club c : list5Clubs) {
                    JSONObject obj = clubService.setTopClub2Json(c, sourceAgent);
                    Map<String, Object> map = clubService.getAdminTypeAndIdByMember(clubMember, memberApplications, club);
                    int adminType = (Integer) map.get("adminType");
                    obj.put("adminType", adminType);
                    if (adminType > -1) {
                        obj.put("isCheck", checkInService.isCheckInToday(user.getUid(), c.getClubId()));
                    } else {
                        obj.put("isCheck", false);
                    }
                    arrIndex.add(obj);
                }
            }
        }
        if (source == 2) {
            json.put("dataStart", DateUtils.format(DateUtils.getLastWeekStart()).replaceAll("-", "."));
            json.put("dataEnd", DateUtils.format(DateUtils.getLastWeekEnd()).replaceAll("-", "."));
        } else {
            json.put("dataStart", DateUtils.getLastWeekStart());
            json.put("dataEnd", DateUtils.getLastWeekEnd());
        }
        json.put("data", arr);
        json.put("clubIndexData", arrIndex);
        print(response, json.toJSONString(), callback);
    }

    /**
     * 获取地区排名
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/club/listTopForRegion.do", method = RequestMethod.GET)
    public void listTopForRegion(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setCacheHeader(response, 1800);//缓存半小时
        WebUtils.setEncoding(request, response);
        String callback = WebUtils.param(request, "callback", "");
        JSONObject json = new JSONObject();
        JSONArray arr = new JSONArray();
        JSONArray arrIndex = new JSONArray();//用于保存本车友会排名前后2名的信息
        int source = WebUtils.paramInt(request, "source", 1);
        int sourceAgent = WebUtils.paramInt(request, "source_agent", DEF_SOURCE_AGENT);
        long userId = WebUtils.paramLong(request, "userId", 0);
        //是否需要返回后面数组，用于首页排行榜是否有变化显示，0则返回，1只返回排名变化
        int showType = WebUtils.paramInt(request, "showType", 0);
        User user = userService.findUser(userId);
        ClubMember clubMember = null;
        Club club = null;
        List<MemberApplication> memberApplications = null;
        if (user != null && user.getUid() > 0) {
            clubMember = memberService.findClubMemberByUserId(user.getUid());
            memberApplications = memberService.listMemberApplicationsByUserId(user.getUid());
            // 如果此用户已经加入车友会,返回车友会全国，车系，地区排名
            if (clubMember != null) {
                club = clubService.getClub(clubMember.getClubId());
                json = getClubRank(clubMember, club);
            }
        }
        long provinceIdByClubId = club == null ? 0 : club.getProvinceId();
        List<Club> list = clubService.listClubBySortForList(ClubService.SORT_REGION_TYPE, PAGE_NUM, PAGE_SIZE, 0L,
                provinceIdByClubId, 0, 0);
        for (Club c : list) {
            JSONObject obj = clubService.setTopClub2Json(c, sourceAgent);
            Map<String, Object> map = clubService.getAdminTypeAndIdByMember(clubMember, memberApplications, c);
            int adminType = (Integer) map.get("adminType");
            obj.put("adminType", adminType);
            if (adminType > -1) {
                obj.put("isCheck", checkInService.isCheckInToday(
                        user.getUid(), c.getClubId()));
            } else {
                obj.put("isCheck", false);
            }
            arr.add(obj);
        }
        // 获取本车友会排名的前后2名
        if (club != null && club.getProvinceRank() > 0L) {
            int beginRank = club.getProvinceRank() - 2 <= 0 ? 1 : club.getProvinceRank() - 2;
            int endRank = club.getProvinceRank() + 2;
            List<Club> list5Clubs = clubService.listClubBySortForList(ClubService.SORT_REGION_TYPE, PAGE_NUM, PAGE_SIZE,
                    0L, club.getProvinceId(), beginRank, endRank);
            for (Club c : list5Clubs) {
                JSONObject obj = clubService.setTopClub2Json(c, sourceAgent);
                Map<String, Object> map = clubService.getAdminTypeAndIdByMember(clubMember, memberApplications, c);
                int adminType = (Integer) map.get("adminType");
                obj.put("adminType", adminType);
                if (adminType > -1) {
                    obj.put("isCheck", checkInService.isCheckInToday(user.getUid(), c.getClubId()));
                } else {
                    obj.put("isCheck", false);
                }
                arrIndex.add(obj);
            }
        }
        if (source == 2) {
            json.put("dataStart", DateUtils.format(DateUtils.getLastWeekStart()).replaceAll("-", "."));
            json.put("dataEnd", DateUtils.format(DateUtils.getLastWeekEnd()).replaceAll("-", "."));
        } else {
            json.put("dataStart", DateUtils.getLastWeekStart());
            json.put("dataEnd", DateUtils.getLastWeekEnd());
        }
        json.put("data", arr);
        json.put("clubIndexData", arrIndex);
        print(response, json.toJSONString(), callback);
    }
}
